<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2020/5/25
 * Time: 9:59
 */

namespace app\index\controller;


use app\service\CommissionService;
use app\service\EalspellCommissionService;
use app\service\IGeTuiService;
use app\service\TaskService;
use Endroid\QrCode\QrCode;
use Redis\Redis;
use think\Controller;
use think\Db;
use think\Log;
use think\Request;
use Yansongda\Pay\Exceptions\BusinessException;
use Yansongda\Pay\Exceptions\GatewayException;
use Yansongda\Pay\Pay;

class Payment extends Controller
{
    # 商户id
    public $bizId;
    # 微信提现config
    private $wxDepositConfig = [
        'appid' => 'wxb4d0f405482e31c5', // APP APPID
        'app_id' => 'wxb4d0f405482e31c5', // 公众号 APPID
        'miniapp_id' => 'wxb4d0f405482e31c5', // 小程序 APPID
        'mch_id' => '1573261001',
        'key' => 'youpilive13236999488youpilive488',
        'notify_url' => 'http://coo.elianchefu.com/index/Payment/payBackWx',//支付回调地址
        'cert_client' => ROOT_PATH . '../extend/cert/apiclient_cert.pem', // optional，退款等情况时用到
        'cert_key' => ROOT_PATH . '../extend/cert/apiclient_key.pem',// optional，退款等情况时用到
        'log' => [ // optional
            'file' => '../runtime/payLogs//wechat.log',
            'level' => 'info', // 建议生产环境等级调整为 info，开发环境为 debug
            'type' => 'single', // optional, 可选 daily.
            'max_file' => 30, // optional, 当 type 为 daily 时有效，默认 30 天
        ],
        'http' => [ // optional
            'timeout' => 5.0,
            'connect_timeout' => 5.0,
            // 更多配置项请参考 [Guzzle](https://guzzle-cn.readthedocs.io/zh_CN/latest/request-options.html)
        ],
        // 'mode' => 'dev',
    ];
    # 微信支付config
    private $wxConfig = [
        'appid' => 'wx65ed2042b845dad8', // APP APPID
        'app_id' => 'wx65ed2042b845dad8', // 公众号 APPID
        'miniapp_id' => 'wx65ed2042b845dad8', // 小程序 APPID
        'mch_id' => '1573261001',
        'key' => 'youpilive13236999488youpilive488',
        'notify_url' => 'http://coo.elianchefu.com/index/Payment/payBackWx',//支付回调地址
        'cert_client' => ROOT_PATH . '../extend/cert/apiclient_cert.pem', // optional, 退款，红包等情况时需要用到
        'cert_key' => ROOT_PATH . '../extend/cert/apiclient_key.pem',// optional, 退款，红包等情况时需要用到
        'log' => [ // optional
            'file' => '../runtime/payLogs//wechat.log',
            'level' => 'info', // 建议生产环境等级调整为 info，开发环境为 debug
            'type' => 'single', // optional, 可选 daily.
            'max_file' => 30, // optional, 当 type 为 daily 时有效，默认 30 天
        ],
        'http' => [ // optional
            'timeout' => 5.0,
            'connect_timeout' => 5.0,
            // 更多配置项请参考 [Guzzle](https://guzzle-cn.readthedocs.io/zh_CN/latest/request-options.html)
        ],
        // 'mode' => 'dev',
    ];

    # 支付宝支付config
    private $aliConfig = [
        'app_id' => '2021002114641063',
        'notify_url' => 'http://coo.elianchefu.com/index/Payment/payBackAli',
        'return_url' => 'http://coo.elianchefu.com/index/Payment/payBackAli',
        'merchant_private_key' => "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQDHDBAl+Fg3wIa741xCYZR79mMZCqwYCJ1HjwO4XV0AsXF4X3RcT/q+IhJymJmJ6kvta7ilClctQRWoSnyKUy5gd+foi0w3xZe7dfAswRzN6QdmcimUeOVDYEjG8/oS57yJrLSaGdROoQRqde8O+rV6Hzt1efL+UIM90KmJ99+Pa4I3Emv7atbyulvsSVjrN/AOuAL2WGOS7rTL2Q88J72sgUIOJ6bk9TFYyd5ydedQurDagv1DXTohCAJtFIQDnOZn/1QX+vRX4d8uePmhjNQ6v02U3jp6/z+wp68718WzMRuO/FMtbxLu93Bo8aH6WP5QkNal9zuP4RfxDALtacLvAgMBAAECggEAJSKwBJV/x+8IdBdoCA5yiGogdPSTxOweg9I/zG7GwjFYzS9p4yscycpLjMvBoYRv4/y79zalqxDAfKRg9eGs/lyAjNcoQiOAOn43b/IbcKMwOUHFVij0BQz6pvuvxUUs3La2/yUgggbybvZPwoitwPoAutskpaPZyHecmdv//p6ogW6fLqWyAkItNcDt/6De3A8TR4t209MfXvKT0NHFucYMPQF2rFl973bb9STPncpzrcU0fRW4tlpOuuLoOlMX03rC9XV3hsmXP9vtwM2ydB9hvJy+5Uot72Cd92hnXE/FLvPqbEzSw8f9NkAbAK0jjGtr1wkCnxNtqSLx3g8h6QKBgQD6FqTbz4/RtqRqvNzlyYhNQMstvCYSAPFQtOv1Ikk1m6yCScdm1NaJE3ds7Lu9Vu709+BFCz3usOljff2IdovinKH2OjahLQSHLdShC+qjQ8NPFsEzdGR9R3J2zJHNdqYpU9V+WqLgoPwSwgUDslDM4ffNdwYmFXiQSgv8U+T5awKBgQDLwI21v4H7P6QjZO+17kRSfZG6T1k7tKm4t26wC6P6v6l4tHLu2ejiahz1+LLXSCmgtD22ebGA/nNk5EsyodRbPMUElcvs54yBEm9XSsCg8Op+VfITEGFzDAviEWICcFwZY7ndrOVh91PjhRqctzS40lf1GE/KVR41RfbQNF7pjQKBgQDT+HVrShZgbioVvlaM/bBlqlGMRjkOcXYYLgEBGTpsEbK6C8bTRftA3BsRW+YUqaaIQ8D3RHwN4C0xgwxtqe0O+ivdA6JiIkIAQbxDdFJAZ6MXWfYPosu50+EVCHdcawCTbtc57aC4PDrruz98zprlzXG32PaBORmjUt+t0330WQKBgBsNFINlyp8N4v/j/cNcv+tnyno+4K0Bnmrsx6BN21aGLbzd0EiP29B7oB60ByJ37Tbt1yer3nouzik9+hHd1HDMj6e9L5bjYw8b4HZpcUus0KU3Se1oBlgc6FL6VdXXDxM730hkFQw9pwCVAmR+GlzTaGQc9zL4vAr8n/kiittdAoGBALqZbC4st0K2H865QLTk/ZHWa7zl3a+iuTOo8/HOugpURULfdRP4sY3QyJpwwq1MMLq84k9UP1HjssmNr9Jpr1MQyf3yacXNzqv2j0aDppJW+VOPRugZ58W/B2BRfowRhLAKDyNlPoUQS3seV6kZjHpwftMKyBsBqbAEU4iAUrQI",
        'alipay_public_key' => 'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAojSPnrmQl1GIIvNrRalo6QsnAYU3Wff3grKnHMoi0xZ6ftKMROB6tUY91AVa85CHld7MkrwZHlvDSjUrtzIfBnevpOSCUKIVgSEf4dO3WMbSlLDU7Pu5xz9gCM7WA6tbtvmszgwmk6piZDenSZcx08e4t1QIeBP5YxGjHM4lk8hPFgdSsP1frY7zVGw+fZxKl+QOcW6MtX89NqQOVe84IgSej4cWhTuSwBdKA5SoHLW2vuauvTwAF+qpETkUO4MzzPqYPTUe05Ap6NDbtVhctFerdbRudjfnYZe7Bgj4ukSz0Jc7eJ/BH/6jTZXYMQW7Ck7DwVShapp4pJoaLag11wIDAQAB',
        'log' => [ // optional
            'file' => '../runtime/payLogs/alipay.log',
            'level' => 'info', // 建议生产环境等级调整为 info，开发环境为 debug
            'type' => 'single', // optional, 可选 daily.
            'max_file' => 30, // optional, 当 type 为 daily 时有效，默认 30 天
        ],
        'http' => [ // optional
            'timeout' => 5.0,
            'connect_timeout' => 5.0,
            // 更多配置项请参考 [Guzzle](https://guzzle-cn.readthedocs.io/zh_CN/latest/request-options.html)
        ],
        // 'mode' => 'dev', // optional,设置此参数，将进入沙箱模式
    ];
    # 二维码信息
    protected $QrCodeInfo = '';

    # 订单支付信息
    protected $order = [];

    # 支付方式
    protected $payType = '';

    # redis
    protected $redis;

    /**
     * @var array 门店升级-微信支付config
     */
    private $wx_config = [
        'appid' => 'wxb4d0f405482e31c5', // APP APPID
        'app_id' => 'wx65ed2042b845dad8', // 公众号 APPID
        'mch_id' => '1573261001',
        'key' => 'youpilive13236999488youpilive488',
        'notify_url' => 'http://coo.elianchefu.com/index/Payment/wxPayAPP_notify',//支付回调地址
        'log' => [ // optional
            'file' => '../runtime/payLogs//wechat.log',
            'level' => 'debug', // 建议生产环境等级调整为 info，开发环境为 debug
            'type' => 'single', // optional, 可选 daily.
            'max_file' => 30, // optional, 当 type 为 daily 时有效，默认 30 天
        ],
        'http' => [ // optional
            'timeout' => 5.0,
            'connect_timeout' => 5.0,
            // 更多配置项请参考 [Guzzle](https://guzzle-cn.readthedocs.io/zh_CN/latest/request-options.html)
        ],
        // 'mode' => 'dev',
    ];
    /**
     * @var array 门店升级-支付宝支付
     */
    private $ali_config = [
        'app_id' => '2021002114641063',
        'notify_url' => 'http://coo.elianchefu.com/index/Payment/aliPayAPP_notify',
        'ali_public_key' => 'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAojSPnrmQl1GIIvNrRalo6QsnAYU3Wff3grKnHMoi0xZ6ftKMROB6tUY91AVa85CHld7MkrwZHlvDSjUrtzIfBnevpOSCUKIVgSEf4dO3WMbSlLDU7Pu5xz9gCM7WA6tbtvmszgwmk6piZDenSZcx08e4t1QIeBP5YxGjHM4lk8hPFgdSsP1frY7zVGw+fZxKl+QOcW6MtX89NqQOVe84IgSej4cWhTuSwBdKA5SoHLW2vuauvTwAF+qpETkUO4MzzPqYPTUe05Ap6NDbtVhctFerdbRudjfnYZe7Bgj4ukSz0Jc7eJ/BH/6jTZXYMQW7Ck7DwVShapp4pJoaLag11wIDAQAB',
        // 加密方式： **RSA2**
        'private_key' => 'MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQDHDBAl+Fg3wIa741xCYZR79mMZCqwYCJ1HjwO4XV0AsXF4X3RcT/q+IhJymJmJ6kvta7ilClctQRWoSnyKUy5gd+foi0w3xZe7dfAswRzN6QdmcimUeOVDYEjG8/oS57yJrLSaGdROoQRqde8O+rV6Hzt1efL+UIM90KmJ99+Pa4I3Emv7atbyulvsSVjrN/AOuAL2WGOS7rTL2Q88J72sgUIOJ6bk9TFYyd5ydedQurDagv1DXTohCAJtFIQDnOZn/1QX+vRX4d8uePmhjNQ6v02U3jp6/z+wp68718WzMRuO/FMtbxLu93Bo8aH6WP5QkNal9zuP4RfxDALtacLvAgMBAAECggEAJSKwBJV/x+8IdBdoCA5yiGogdPSTxOweg9I/zG7GwjFYzS9p4yscycpLjMvBoYRv4/y79zalqxDAfKRg9eGs/lyAjNcoQiOAOn43b/IbcKMwOUHFVij0BQz6pvuvxUUs3La2/yUgggbybvZPwoitwPoAutskpaPZyHecmdv//p6ogW6fLqWyAkItNcDt/6De3A8TR4t209MfXvKT0NHFucYMPQF2rFl973bb9STPncpzrcU0fRW4tlpOuuLoOlMX03rC9XV3hsmXP9vtwM2ydB9hvJy+5Uot72Cd92hnXE/FLvPqbEzSw8f9NkAbAK0jjGtr1wkCnxNtqSLx3g8h6QKBgQD6FqTbz4/RtqRqvNzlyYhNQMstvCYSAPFQtOv1Ikk1m6yCScdm1NaJE3ds7Lu9Vu709+BFCz3usOljff2IdovinKH2OjahLQSHLdShC+qjQ8NPFsEzdGR9R3J2zJHNdqYpU9V+WqLgoPwSwgUDslDM4ffNdwYmFXiQSgv8U+T5awKBgQDLwI21v4H7P6QjZO+17kRSfZG6T1k7tKm4t26wC6P6v6l4tHLu2ejiahz1+LLXSCmgtD22ebGA/nNk5EsyodRbPMUElcvs54yBEm9XSsCg8Op+VfITEGFzDAviEWICcFwZY7ndrOVh91PjhRqctzS40lf1GE/KVR41RfbQNF7pjQKBgQDT+HVrShZgbioVvlaM/bBlqlGMRjkOcXYYLgEBGTpsEbK6C8bTRftA3BsRW+YUqaaIQ8D3RHwN4C0xgwxtqe0O+ivdA6JiIkIAQbxDdFJAZ6MXWfYPosu50+EVCHdcawCTbtc57aC4PDrruz98zprlzXG32PaBORmjUt+t0330WQKBgBsNFINlyp8N4v/j/cNcv+tnyno+4K0Bnmrsx6BN21aGLbzd0EiP29B7oB60ByJ37Tbt1yer3nouzik9+hHd1HDMj6e9L5bjYw8b4HZpcUus0KU3Se1oBlgc6FL6VdXXDxM730hkFQw9pwCVAmR+GlzTaGQc9zL4vAr8n/kiittdAoGBALqZbC4st0K2H865QLTk/ZHWa7zl3a+iuTOo8/HOugpURULfdRP4sY3QyJpwwq1MMLq84k9UP1HjssmNr9Jpr1MQyf3yacXNzqv2j0aDppJW+VOPRugZ58W/B2BRfowRhLAKDyNlPoUQS3seV6kZjHpwftMKyBsBqbAEU4iAUrQI',
        //'app_cert_path'=>ROOT_PATH.'../extend/cert/appCertPublicKey_2021002114641063.crt', // 应用证书
        //'alipay_root_cert_path'=>ROOT_PATH.'../extend/cert/alipayRootCert.crt',// 支付宝根证书
        //'alipay_cert_path'=>ROOT_PATH.'../extend/cert/alipayCertPublicKey_RSA2.crt', // 支付宝公钥证书
        'log' => [ // optional
            'file' => 'runtime/logs/alipay.log',
            'level' => 'debug', // 建议生产环境等级调整为 info，开发环境为 debug
            'type' => 'single', // optional, 可选 daily.
            'max_file' => 30, // optional, 当 type 为 daily 时有效，默认 30 天
        ],
        'http' => [ // optional
            'timeout' => 5.0,
            'connect_timeout' => 5.0,
            // 更多配置项请参考 [Guzzle](https://guzzle-cn.readthedocs.io/zh_CN/latest/request-options.html)
        ],
        //'mode' => 'dev', // optional,设置此参数，将进入沙箱模式
    ];

    /**
     * Payment constructor.
     * @param array $order
     */
    public function __construct(array $order = array())
    {
        $this->order = $order;
        header('Access-Control-Allow-Origin:*');  //支持全域名访问，不安全，部署后需要固定限制为客户端网址
        header('Access-Control-Allow-Methods:POST,GET,OPTIONS,DELETE'); //支持的http 动作
        header('Access-Control-Allow-Headers:Access-Control-Allow-Headers, Origin,Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Authorization , Access-Control-Request-Headers,token');  //响应头 请按照自己需求添加。
        if (strtoupper($_SERVER['REQUEST_METHOD']) == 'OPTIONS') {
            exit;
        }
        $this->redis = new Redis();
    }

    /**
     * @param $data
     * @return \Symfony\Component\HttpFoundation\Response
     * @content 门店升级-微信APP支付
     */
    public function wxPayAPP($data)
    {
        $pay = Pay::wechat($this->wx_config)->app($data);
        return $pay;
    }

    /**
     * @return \Symfony\Component\HttpFoundation\Response
     * @throws \Yansongda\Pay\Exceptions\InvalidArgumentException
     * @content 门店升级-微信支付回调
     */
    public function wxPayAPP_notify()
    {
        $pay = Pay::wechat($this->wx_config);
        try {
            $data = $pay->verify(); // 是的，验签就这么简单！
            if (!is_array($data)) {
                $data = json_decode($data, true);
            }
            Db::table('aaa')->insert(array('info' => json_encode($data), 'type' => 'wxPayAPP_notify'));
            if (!empty($data)) {
//                $data = json_decode($data, true);
                if (array_key_exists('return_code', $data) and $data['return_code'] == 'SUCCESS') {
                    if (array_key_exists('result_code', $data) and $data['result_code'] == 'SUCCESS') {
                        $attach = json_decode($data['attach'], true);
                        $this->bizUpgradeSuccess($attach['biz_id'], $attach['over_time'], $data['total_fee'] / 100, $data['out_trade_no'], 1);
                    }
                }
            }
        } catch (\Exception $e) {
            // $e->getMessage();
        }
        return $pay->success()->send();// laravel 框架中请直接 `return $pay->success()`
    }

    /**
     * @param $order
     * @return \Symfony\Component\HttpFoundation\Response
     * @content 门店升级-支付宝支付
     */
    public function aliPayAPP($order)
    {
        $alipay = Pay::alipay($this->ali_config)->app($order);
        return $alipay;
    }

    /**
     * @return \Symfony\Component\HttpFoundation\Response
     * @content 门店升级-支付宝支付
     */
    public function aliPayAPP_notify()
    {
        $alipay = Pay::alipay($this->ali_config);
        try {
            $data = $alipay->verify(); // 是的，验签就这么简单！
            if (!is_array($data)) {
                $data = json_decode($data, true);
            }
            Db::table('aaa')->insert(array('info' => json_encode($data), 'type' => 'aliPayAPP_notify'));
            // 请自行对 trade_status 进行判断及其它逻辑进行判断，在支付宝的业务通知中，只有交易通知状态为 TRADE_SUCCESS 或 TRADE_FINISHED 时，支付宝才会认定为买家付款成功。
            // 1、商户需要验证该通知数据中的out_trade_no是否为商户系统中创建的订单号；
            // 2、判断total_amount是否确实为该订单的实际金额（即商户订单创建时的金额）；
            // 3、校验通知中的seller_id（或者seller_email) 是否为out_trade_no这笔单据的对应的操作方（有的时候，一个商户可能有多个seller_id/seller_email）；
            // 4、验证app_id是否为该商户本身。
            // 5、其它业务逻辑情况
            if (array_key_exists('trade_status', $data) and ($data['trade_status'] == 'TRADE_SUCCESS' or $data['trade_status'] == 'TRADE_FINISHED')) {
                # 支付成功
                $passback_params = json_decode(urldecode($data['passback_params']), true);
//                Db::table('aaa')->insert(array('info' => json_encode($passback_params), 'type' => '$passback_params'));
                $this->bizUpgradeSuccess($passback_params['biz_id'], $passback_params['over_time'], $data['total_amount'], $data['out_trade_no'], 2);
            }
        } catch (\Exception $e) {
            // $e->getMessage();
        }

        return $alipay->success()->send();// laravel 框架中请直接 `return $alipay->success()`
    }

    /**
     * @param $biz_id
     * @param $over_time
     * @param $pay_price
     * @param $out_trade_no
     * @param $pay_type
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     * @content 门店升级- 修改信息
     */
    function bizUpgradeSuccess($biz_id, $over_time, $pay_price, $out_trade_no, $pay_type)
    {
        $redis = new Redis();
        $status = $redis->lock('bizUpgradeSuccess' . $biz_id);
        if (!$status) {
            return;
        }

        # 判断是否已经修改过数据
        $recommend_status = Db::table('biz')->where(array('id' => $biz_id))->value('recommend_status');
        if ($recommend_status == 1) {
            return;
        }
        # 查询是不是首次
        $upgradeLog = Db::table('biz_log_upgrade')->where(array('biz_id' => $biz_id))->count();
        if ($upgradeLog > 0) {
            # 续费
            $upgrade_type = 2;
        } else {
            # 首次升级
            $upgrade_type = 1;
        }
        # 修改门店信息
        $res = Db::table('biz')->where(array('id' => $biz_id))->update(array(
            'recommend_status' => 1,
            'expair_time' => $over_time,
            'create_pro_num'=>100
        ));
        # 加记录
        Db::table('biz_log_upgrade')->insert(array(
            'biz_id' => $biz_id,
            'create_time' => date('Y-m-d H:i:s'),
            'type' => $upgrade_type,
            'over_time' => $over_time,
            'pay_price' => $pay_price,
            'out_trade_no' => $out_trade_no,
            'pay_type' => $pay_type
        ));
        # 查询门店代理id
        $agent_id = Db::table('biz')->where(array('id' => $biz_id))->value('agent_id');
        if (!empty($agent_id)) {
            if ($upgradeLog > 0) {
                # 续费
                EalspellCommissionService::merchantsUpgrade($agent_id, $pay_price, $biz_id);
            } else {
                # 首次升级
                EalspellCommissionService::merchantsCharge($agent_id, $pay_price, $biz_id);
            }
        }
        $redis->unlock('bizUpgradeSuccess' . $biz_id);

    }

    /**
     * @content 生成二维码
     */
    function generateQrCode()
    {
        if (!empty($this->QrCodeInfo)) {
            $qrcode = new QrCode($this->QrCodeInfo);
            ob_end_clean();
            header('Content-Type: ' . $qrcode->getContentType());
            echo $qrcode->writeString();
        }
    }


    /**
     * @return array
     * @content 微信扫码支付
     */
    function wxPay()
    {
        $res = Pay::wechat($this->wxConfig)->scan($this->order);
        if ($res->result_code == 'SUCCESS') {
//            $this->QrCodeInfo = $res->code_url;
//            $this->generateQrCode();
            return array('status' => true, 'code_url' => $res->code_url);
        } else {
            return array('status' => false);
        }
    }

    /**
     * @return array
     * @content 微信-付款码支付
     */
    function wxPay_pos()
    {
        $res = Pay::wechat($this->wxConfig)->pos($this->order);
        if ($res->result_code == 'SUCCESS') {
            return array('status' => true);
        } else {
            return array('status' => false);
        }
    }

    /**
     * @throws \Yansongda\Pay\Exceptions\InvalidArgumentException
     * @content 微信支付回调
     */
    function payBackWx()
    {
        Db::table('aaa')->insert(array('info' => '微信支付啊回调啊啊啊', 'type' => 'wx'));
//        $testxml = file_get_contents("php://input");
//        $jsonxml = json_encode(simplexml_load_string($testxml, 'SimpleXMLElement', LIBXML_NOCDATA));
//        $callBackRes = json_decode($jsonxml, true);

//        Db::table('aaa')->insert(array('info' => $jsonxml, 'type' => 'wx'));
        # 处理订单--支付成功
//        if ($callBackRes['result_code'] == 'SUCCESS') {
//            # 修改redis中的订单状态为支付成功(1->支付中  2->支付成功 3->支付失败)
//            $this->redis->hSet('orderPayStatus', $callBackRes['out_trade_no'], 2);
//            $this->paySuccess($callBackRes['out_trade_no'], 1, $callBackRes['attach']['pay_price']);
//        }
        echo(Pay::wechat($this->wxConfig)->success()->getContent());
    }

    /**
     * @return array
     * @content 支付宝扫码支付
     */
    function aliPay()
    {
        $res = Pay::alipay($this->aliConfig)->scan($this->order);
        if ($res->result_code == 'SUCCESS') {
//            $this->QrCodeInfo = $res->qr_code;
//            $this->generateQrCode();
            return array('status' => true, 'code_url' => $res->qr_code);
        } else {
            return array('status' => false);
        }
    }

    /**
     * @return array
     * @content 支付宝-付款码支付
     */
    function aliPay_pos()
    {
        $res = Pay::alipay($this->aliConfig)->pos($this->order);
        if ($res->code == '10000' and $res->msg == 'Success') {
            return array('status' => true);
        } else {
            return array('status' => false, 'msg' => $res);
        }
    }

    /**
     * @return array
     * @throws GatewayException
     * @throws \Yansongda\Pay\Exceptions\InvalidArgumentException
     * @throws \Yansongda\Pay\Exceptions\InvalidConfigException
     * @throws \Yansongda\Pay\Exceptions\InvalidSignException
     * @content 查询订单状态
     */
    function findOrderStatus()
    {
        $order = [
            'out_trade_no' => $this->order['out_trade_no'],
        ];
        if ($this->order['payment'] == 'wx') {
            # 微信查询订单
            $result = Pay::wechat($this->wxConfig)->find($order);
            if ($result->return_code == 'SUCCESS' and $result->result_code == 'SUCCESS') {
                if ($result->trade_state == 'SUCCESS') {
                    return array('status' => true, 'is_continue' => 0, 'code' => 'SUCCESS', 'msg' => '支付成功');
                } elseif ($result->trade_state == 'USERPAYING') {
                    return array('status' => true, 'is_continue' => 1, 'code' => 'USERPAYING', 'msg' => '用户支付中');
                } else {
                    return array('status' => false, 'is_continue' => 0, 'code' => $result->state, 'msg' => '支付失败');
                }
            } else {
                return array('status' => true, 'is_continue' => 1, 'code' => 'FAIL', 'msg' => '查询失败');
            }
        } else {
            # 支付宝查询订单
            $result = Pay::alipay($this->aliConfig)->find($order);
            if ($result->code == '10000') {
                if ($result->trade_status == 'TRADE_SUCCESS') {
                    return array('status' => true, 'is_continue' => 0, 'code' => 'SUCCESS', 'msg' => '支付成功');
                } elseif ($result->trade_status == 'WAIT_BUYER_PAY') {
                    return array('status' => true, 'is_continue' => 1, 'code' => 'USERPAYING', 'msg' => '用户支付中');
                } else {
                    return array('status' => false, 'is_continue' => 0, 'code' => $result->trade_status, 'msg' => '支付失败');
                }
            } else {
                return array('status' => true, 'is_continue' => 1, 'code' => 'FAIL', 'msg' => '查询失败');
            }
        }
    }

    /**
     * @content 支付宝支付回调
     */
    function payBackAli()
    {
        $testxml = $_POST;
        $jsonxml = json_encode($testxml);
        Db::table('aaa')->insert(array('info' => $jsonxml, 'type' => 'ali-post'));
//        $callBackRes = json_decode($jsonxml, true);
//        # 处理订单--支付成功
//        if ($callBackRes['trade_status'] === 'TRADE_SUCCESS') {
//            # 支付成功,修改订单支付状态为支付成功(1->支付中  2->支付成功 3->支付失败)
//            $this->redis->hSet('orderPayStatus', $callBackRes['out_trade_no'], 2);
//            $this->paySuccess($callBackRes['out_trade_no'], 2, $callBackRes['body']['pay_price']);
//        }
        echo(Pay::alipay($this->aliConfig)->success()->getContent());
    }

    /**
     * @throws GatewayException
     * @throws \Yansongda\Pay\Exceptions\InvalidConfigException
     * @throws \Yansongda\Pay\Exceptions\InvalidSignException
     * @content 支付宝退款
     */
    function refund_ali()
    {
        $result = Pay::alipay($this->aliConfig)->refund($this->order);
        if ($result->alipay_trade_refund_response->code == '10000') {
            return array('status' => true, 'msg' => '退款成功');
        } else {
            return array('status' => false, 'msg' => $result->alipay_trade_refund_response->sub_msg);
        }
    }

    /**
     * @throws GatewayException
     * @throws \Yansongda\Pay\Exceptions\InvalidArgumentException
     * @throws \Yansongda\Pay\Exceptions\InvalidSignException
     * @content 微信退款
     */
    function refund_wx()
    {
        $result = Pay::wechat($this->wxConfig)->refund($this->order);
        $res = json_decode($result, true);
        if (array_key_exists('return_code', $res) and !empty($res['return_code']) and $res['return_code'] == 'SUCCESS') {
            return array('status' => true, 'msg' => '退款成功', 'info' => $res);
        } else {
            return array('status' => false, 'msg' => $res['return_msg'], 'info' => $res);
        }
    }

    /**
     * @return array
     * @throws BusinessException
     * @throws GatewayException
     * @throws \Yansongda\Pay\Exceptions\InvalidArgumentException
     * @throws \Yansongda\Pay\Exceptions\InvalidSignException
     * @content 微信企业付款
     */
    function transfers()
    {
        $res = Pay::wechat($this->wxDepositConfig)->transfer($this->order);
        $returnInfo = $res->toArray();
        if ($returnInfo['return_code'] == 'SUCCESS' and $returnInfo['result_code'] == 'SUCCESS') {
            return array('status' => true, 'returnCode' => 'SUCCESS', 'msg' => '提现成功', 'payment_no' => $returnInfo['payment_no'], 'payment_time' => $returnInfo['payment_time']);
        } else {
            # 查询订单信息
            $findReturn = Pay::wechat($this->wxConfig)->find(['partner_trade_no' => $this->order['order_number']], 'transfer');
            $findInfo = $findReturn->toArray();
            if ($findInfo['return_code'] == 'SUCCESS' and $findInfo['result_code'] == 'SUCCESS' and $findInfo['status'] == 'SUCCESS') {
                return array('status' => true, 'returnCode' => 'SUCCESS', 'msg' => '提现成功', 'payment_no' => $findInfo['detail_id'], 'payment_time' => $findInfo['payment_time']);
            } else {
                # 失败
                if (!isset($findInfo['return_code']) || 'SUCCESS' != $findInfo['return_code']) {
                    throw new GatewayException('Get Wechat API Error:' . ($findInfo['return_msg'] ?? $findInfo['retmsg'] ?? ''), $findInfo);
                }

                if (isset($findInfo['result_code']) && 'SUCCESS' != $findInfo['result_code']) {
                    throw new BusinessException('Wechat Business Error: ' . $findInfo['err_code'] . ' - ' . $findInfo['err_code_des'], $findInfo);
                }

                return array('status' => true, 'returnCode' => $findInfo['status'], 'reason' => $findInfo['reason'], 'payment_no' => $findInfo['detail_id'], 'payment_time' => $findInfo['payment_time']);
            }
        }
    }

    /**
     * @return array
     * @throws GatewayException
     * @throws \Yansongda\Pay\Exceptions\InvalidArgumentException
     * @throws \Yansongda\Pay\Exceptions\InvalidSignException
     * @content 查询企业转账订单信息
     */
    function findOrderInfo()
    {
        $res = Pay::wechat($this->wxConfig)->find($this->order, 'transfer');
        $findInfo = $res->toArray();
        if ($findInfo['return_code'] == 'SUCCESS' and $findInfo['result_code'] == 'SUCCESS' and $findInfo['status'] == 'SUCCESS') {
            return array('status' => true, 'returnCode' => 'SUCCESS', 'msg' => '提现成功', 'payment_no' => $findInfo['detail_id'], 'payment_time' => $findInfo['payment_time']);
        } else {
            # 失败
            return array('status' => true, 'returnCode' => $findInfo['status'], 'reason' => $findInfo['reason'], 'payment_no' => $findInfo['detail_id'], 'payment_time' => $findInfo['payment_time']);
        }
    }


    /**
     * @return array
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @content 余额支付
     */
    function balancePay()
    {
        if (!empty($this->order)) {
            if (strlen($this->order['auth_code']) == 4) {
                $valicode = valipaypassword($this->order['auth_code'], $this->order['member_id']);
            } else {
                //$valicode = getsPayInfo($this->order['auth_code'], $this->order['member_id']);
                $valicode = payCodeVerify($this->order['member_id'], $this->order['auth_code']);
            }
            if ($valicode['status'] == true) {
                $member_balance = Db::table('member_mapping')->field('member_balance')
                    ->where(array('member_id' => $this->order['member_id']))
                    ->value('member_balance');

                if (getsPriceFormat($member_balance) < getsPriceFormat($this->order['pay_money'])) {
                    return array('status' => false, 'msg' => '用户余额不足');
                } else {
                    if (floatval($this->order['pay_money']) == 0) {
                        # 支付成功
                        $this->paySuccess($this->order['out_trade_no'], 5, 0);
                        return array('status' => true, 'msg' => '支付成功');
                    } else {
                        # 扣除用户余额
                        $withhold = Db::table('member_mapping')->where(array('member_id' => $this->order['member_id']))
                            ->setDec('member_balance', $this->order['pay_money']);
                        if ($withhold) {
                            # 支付成功
                            $this->paySuccess($this->order['out_trade_no'], 5, $this->order['pay_money']);
                            return array('status' => true, 'msg' => '支付成功');
                        } else {
                            return array('status' => false, 'msg' => '支付失败,用户余额扣除失败');
                        }
                    }
                }
            } else {
                return array('status' => false, 'msg' => $valicode['msg']);
            }
        } else {
            return array('status' => false, 'msg' => '订单支付信息为空');
        }
    }

    /**
     * @return array
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     * @content 卡券支付
     */
    function voucherPay()
    {
        if (empty($this->order)) {
            return array('status' => false, 'msg' => '订单支付信息为空');
        }
        # 查询订单信息
        $orderInfo = Db::table('orders')->field('id,order_type,member_id,pay_type,order_number,order_price,voucher_price')
            ->where(array('order_number' => $this->order['out_trade_no']))->find();
        if (empty($orderInfo)) {
            return array('status' => false, 'msg' => '订单信息为空');
        }
        $this->order['pay_money'] = $orderInfo['order_price'];
        # 预约订单直接核销成功 不需要更改订单的支付方式
        $ordersType = true;
        if ($orderInfo['order_number'] == $this->order['voucher_id']) {
            if ($orderInfo['order_type'] == 3) {
                # 预约订单,使用订单编号核销
                # 卡券核销码相同,可以核销 , 将预约订单第一项改为已完成
                $order_server = Db::table('order_server')->field('id,price')->where(array('order_number' => $orderInfo['order_number']))->order(array('id' => 'asc'))->find();
                if (!empty($order_server)) {
                    Db::table('order_server')->where(array('id' => $order_server['id']))->update(array('status' => 6));
                    Db::table('order_server')->where(array('appointment_status' => 2, 'is_appointment' => 2))->update(array('status' => 6));
                    # 判断是否需要进行继续支付,查询工单中待结算的项目
                    $workOrderCountInfo = Db::table('orders o')
                        ->field("o.id,
                            (select count(os.id) from order_server os where os.order_number = o.order_number and os.status = 4) servercount,
                            (select count(ob.id) from order_biz ob where ob.order_number = o.order_number and ob.status = 2) bizcount
                            ")
                        ->where(array('o.order_number' => $orderInfo['order_number']))
                        ->find();
                    $workOrderCount = intval($workOrderCountInfo['servercount']) + intval($workOrderCountInfo['bizcount']);
                    if ($workOrderCount >= 1) {
                        # 判断剩余订单金额是否为0
                        $money_server = Db::table('order_server')->where(array('order_number' => $orderInfo['order_number']))->sum('price');
                        $money_biz = Db::table('order_biz')->where(array('order_number' => $orderInfo['order_number']))->sum('pro_price');
                        if (($money_server + $money_biz) > 0) {
                            /*完成任务   sp*/
                            finishTaskCondition($orderInfo['member_id'], 3);
                            # 请继续支付
                            return array('status' => true, 'is_continue' => 1, 'msg' => '核销成功,该订单还有未支付的项目，请继续支付');
                        } else {
                            # 不需要继续支付
                            $orderCancelStatus = true;
                            $orderPrice = $this->order['pay_money'];//- $order_server['price']
                            $ordersType = false;
                        }
                    } else {
                        # 核销成功,不需要继续支付
                        $orderCancelStatus = true;
                        $orderPrice = $this->order['pay_money'];//- $order_server['price']
                        $ordersType = false;
                    }
                } else {
                    return array('status' => false, 'msg' => '工单信息为空');
                }
            } else {
                return array('status' => false, 'msg' => '不是预约订单');
            }
        } else {
            # 使用卡券核销
            if (empty($this->order['voucherInfo'])) {
                return array('status' => false, 'msg' => '卡券信息为空');
            }
            # 核销状态,全部完成的状态默认为false
            $orderCancelStatus = false;
            # 判断卡券来源
            if (intval($this->order['voucherInfo']['voucher_id']) == 0) {
//                if($this->order['voucherInfo']['voucher_source']==16){
//                    # 现金红包,查询卡券详情
//                    $voucherInfo = Db::table('redpacket_detail')->where(array('id' => $this->order['voucherInfo']['redpacket_id']))->find();
//                }else {
//                    # 现金红包,查询卡券详情
//                    $voucherInfo = Db::table('redpacket_detail')->where(array('redpacket_id' => $this->order['voucherInfo']['redpacket_id']))->find();
//                }
//                if (empty($voucherInfo)) {
//                    return array('status' => false, 'msg' => '卡券信息为空1');
//                }
                $voucherInfo = Db::table('member_voucher')->where(array('id' => $this->order['voucherInfo']['id']))->find();
                # 现金红包,添加现金卡券使用记录(一天只能使用一次现金抵值券)
                $logCashCoupon = Db::table('log_cashcoupon')->insertGetId(array(
                    'voucher_id' => $this->order['voucherInfo']['id'],
                    'member_id' => $orderInfo['member_id'],
                    'voucher_price' => $this->order['voucherInfo']['voucher_price'],
                    'order_number' => $orderInfo['order_number'],
                    'voucher_type' => $voucherInfo['voucher_type'],
                    'create_time' => date('Y-m-d H:i:s')
                ));
                # 更改用户卡券状态为已核销
                Db::table('member_voucher')->where(array('id' => $this->order['voucherInfo']['id']))->update(array('status' => 2, 'order_id' => $orderInfo['id']));
                # 添加卡券使用记录
                Db::table('log_voucher')->insert(array(
                    'member_id' => $orderInfo['member_id'],
                    'voucher_id' => $this->order['voucherInfo']['voucher_id'],
                    'status' => 2,
                    'create_time' => date('Y-m-d H:i:s'),
                    'type' => 1
                ));
                # 修改订单卡券核销的价格
                Db::table('orders')->where(array('id' => $orderInfo['id']))->setInc('voucher_price', $this->order['voucherInfo']['voucher_price']);
                if (in_array($voucherInfo['voucher_type'], [1, 2, 5, 6])) {
                    # 判断是否需要继续进行支付
                    $orderPrice = floatval($this->order['pay_money']) - floatval($this->order['voucherInfo']['voucher_price']);
                    if ($orderPrice > 0) {
                        /*完成任务*/
                        finishTaskCondition($orderInfo['member_id'], 3);
                        # 需要进行继续支付
                        return array('status' => true, 'is_continue' => 1, 'msg' => '核销成功,该订单还有未支付的项目,请继续支付', 'pay_money' => $orderPrice);
                    } else {
                        # 核销成功,不需要继续支付
                        $orderCancelStatus = true;
                    }
                } elseif ($voucherInfo['voucher_type'] == 4) {
                    # 单独服务抵值券,查询服务工单中该券对应的服务并且是已完成未核销的(取一条)
                    $workOrderInfo = Db::table('order_server')
                        ->field('id,price,server_id')
                        ->where(array('server_id' => $voucherInfo['server_id'], 'coupon_mark' => 1, 'status' => 4, 'custommark' => 1, 'order_number' => $orderInfo['order_number']))
                        ->find();
                    if (empty($workOrderInfo)) {
                        return array('status' => false, 'msg' => '卡券不可用,不存在可核销的服务');
                    }
                    # 将工单id填入刚添加的红包使用记录里
                    Db::table('log_cashcoupon')->where(array('id' => $logCashCoupon))->update(array(
                        'workorder_id' => $workOrderInfo['id'],
                        'voucher_type' => 4,
                        'order_type' => 2
                    ));
                    if ($workOrderInfo['price'] > $this->order['voucherInfo']['voucher_price']) {
                        $_couponPrice = $workOrderInfo['price'] - $this->order['voucherInfo']['voucher_price'];
                        $_couponPrices = $this->order['voucherInfo']['voucher_price'];
                    } else {
                        $_couponPrice = 0;
                        $_couponPrices = $workOrderInfo['price'];
                    }
                    # 工单价格减去现金抵值券的价格
                    if ($_couponPrice == 0) {
                        $couponMark = 2;
                    } else {
                        $couponMark = 1;
                    }
                    Db::table('order_server')->where(array('id' => $workOrderInfo['id']))->update(array('price' => $_couponPrice, 'coupon_mark' => $couponMark));
                    Db::table('order_server')->where(array('id' => $workOrderInfo['id']))->setInc('coupon_price', $_couponPrices);
                    Db::table('member_voucher')->where(array('id' => $this->order['voucherInfo']['id']))->update(array('order_server_id' => $workOrderInfo['id']));
                    # 订单表 ,
//                    Db::table('orders')->where(array('order_number' => $orderInfo['order_number']))->setInc('voucher_price', $this->order['voucherInfo']['voucher_price']);
                    # 判断是否需要继续进行支付
                    //  Db::table('aaa')->insert(array('info'=>$this->order['pay_money']));
                    $orderPrice = floatval($this->order['pay_money']) - floatval($_couponPrices);
                    //  Db::table('aaa')->insert(array('info'=>$orderPrice));
                    if ($orderPrice > 0) {
                        /*完成任务*/
                        finishTaskCondition($orderInfo['member_id'], 3);
                        # 需要进行继续支付
                        return array('status' => true, 'is_continue' => 1, 'msg' => '核销成功,该订单还有未支付的项目,请继续支付', 'pay_money' => $orderPrice);
                    } else {
                        # 核销成功,不需要继续支付
                        $orderCancelStatus = true;
                    }
                } elseif ($voucherInfo['voucher_type'] == 3) {
                    # 单独商品抵值券,查询工单中已结算的商品(商品数量减去卡券核销数量大于1)系统商品
                    $workOrderInfo = Db::table('order_biz')->field('id,pro_price,coupon_price,biz_pro_id')
                        ->where(array('biz_pro_id' => $voucherInfo['server_id'], 'coupon_mark' => 1, 'status' => 2, 'custommark' => 1, 'order_number' => $orderInfo['order_number']))->find();
                    if (empty($workOrderInfo)) {
                        return array('status' => false, 'msg' => '卡券不可用,,不存在可核销的商品');
                    }
                    # 将工单id填土刚才添加的现金红包使用记录里
                    Db::table('log_cashcoupon')->where(array('id' => $logCashCoupon))->update(array('workorder_id' => $workOrderInfo['id'], 'voucher_type' => 3, 'order_type' => 1));
                    Db::table('member_voucher')->where(array('id' => $this->order['voucherInfo']['id']))->update(array('order_server_id' => $workOrderInfo['id']));
                    # 卡券金额写入到工单中(判断是否需要修改卡券核销状态)
                    $price_mark = $workOrderInfo['pro_price'] - $workOrderInfo['coupon_price'] - $this->order['voucherInfo']['voucher_price'];
                    if ($price_mark > 0) {
                        $_data = array('coupon_price' => $this->order['voucherInfo']['voucher_price'] + $workOrderInfo['coupon_price']);
                        $orderPrice = $this->order['pay_money'] - $this->order['voucherInfo']['voucherInfo'];
                    } else {
                        $_data = array('coupon_price' => $workOrderInfo['pro_price'], 'coupon_mark' => 2);
                        $orderPrice = $this->order['pay_money'] - ($workOrderInfo['pro_price'] - $workOrderInfo['coupon_price']);
                    }
                    Db::table('order_biz')->where(array('id' => $workOrderInfo['id']))->update($_data);
                    # 判断是否需要进行支付
                    if ($orderPrice > 0) {
                        /*完成任务   sp*/
                        finishTaskCondition($orderInfo['member_id'], 3);
                        # 需要进行继续支付
                        return array('status' => true, 'is_continue' => 1, 'msg' => '核销成功,该订单还有未支付的项目，请继续支付', 'pay_money' => $orderPrice);
                    } else {
                        # 核销成功,不需要继续支付
                        $orderCancelStatus = true;
                    }
                }
            } else {
                $orderPrice = 0;
                # 普通卡券,查询卡券详情
                if (in_array($this->order['voucherInfo']['voucher_type'], array(11, 12, 13, 14, 15, 16))) {
                    $cardVoucherInfo = Db::table('merchants_voucher')->where(array('id' => $this->order['voucherInfo']['voucher_id']))->find();
                    $cardVoucherInfo['card_type_id'] = $this->order['voucherInfo']['voucher_type'];
                } else {
                    $cardVoucherInfo = Db::table('card_voucher')->where(array('id' => $this->order['voucherInfo']['voucher_id']))->find();
                }
                if (empty($cardVoucherInfo)) {
                    return array('status' => false, 'msg' => '卡券信息为空2');
                }
                if (in_array($this->order['voucherInfo']['voucher_type'], array(11, 12, 13, 14, 15, 16))) {
                    # 现金红包,添加现金卡券使用记录(一天只能使用一次现金抵值券)
                    $logCashCoupon = Db::table('log_cashcoupon')->insertGetId(array(
                        'voucher_id' => $this->order['voucherInfo']['id'],
                        'member_id' => $orderInfo['member_id'],
                        'voucher_price' => $this->order['voucherInfo']['voucher_price'],
                        'order_number' => $orderInfo['order_number'],
                        'voucher_type' => $this->order['voucherInfo']['voucher_type'],
                        'create_time' => date('Y-m-d H:i:s')
                    ));
                    # 更改用户卡券状态为已核销
                    Db::table('member_voucher')->where(array('id' => $this->order['voucherInfo']['id']))->update(array('status' => 2, 'order_id' => $orderInfo['id']));
                    # 添加卡券使用记录
                    Db::table('log_voucher')->insert(array(
                        'member_id' => $orderInfo['member_id'],
                        'voucher_id' => $this->order['voucherInfo']['voucher_id'],
                        'status' => 2,
                        'create_time' => date('Y-m-d H:i:s'),
                        'type' => 1
                    ));
                    # 修改订单卡券核销的价格
                    Db::table('orders')->where(array('id' => $orderInfo['id']))->setInc('voucher_price', $this->order['voucherInfo']['voucher_price']);
                    # 单独服务抵值券,查询服务工单中该券对应的服务并且是已完成未核销的(取一条)
                    $workOrderInfo = Db::table('order_server os')
                        ->field('os.id,os.price,os.server_id')
//                        ->join('service s', 's.id=os.server_id', 'left')
//                        ->where("s.biz_pid != 0")
                        ->where(array('os.coupon_mark' => 1, 'os.status' => 4, 'os.custommark' => 1, 'os.order_number' => $orderInfo['order_number']))
                        ->find();
                    if (empty($workOrderInfo)) {
                        return array('status' => false, 'msg' => '卡券不可用,不存在可核销的服务');
                    }
                    # 将工单id填入刚添加的红包使用记录里
                    Db::table('log_cashcoupon')->where(array('id' => $logCashCoupon))->update(array(
                        'workorder_id' => $workOrderInfo['id'],
                        'voucher_type' => 4,
                        'order_type' => 2
                    ));
                    if ($workOrderInfo['price'] > $this->order['voucherInfo']['voucher_price']) {
                        $_couponPrice = $workOrderInfo['price'] - $this->order['voucherInfo']['voucher_price'];
                        $_couponPrices = $this->order['voucherInfo']['voucher_price'];
                    } else {
                        $_couponPrice = 0;
                        $_couponPrices = $workOrderInfo['price'];
                    }
                    # 工单价格减去现金抵值券的价格
                    if ($_couponPrice == 0) {
                        $couponMark = 2;
                    } else {
                        $couponMark = 1;
                    }
                    Db::table('order_server')->where(array('id' => $workOrderInfo['id']))->update(array('price' => $_couponPrice, 'coupon_mark' => $couponMark));
                    Db::table('order_server')->where(array('id' => $workOrderInfo['id']))->setInc('coupon_price', $_couponPrices);
                    Db::table('member_voucher')->where(array('id' => $this->order['voucherInfo']['id']))->update(array('order_server_id' => $workOrderInfo['id']));
                    # 判断是否需要继续进行支付
                    $orderPrice = floatval($this->order['pay_money']) - floatval($_couponPrices);
                    if ($orderPrice > 0) {
                        /*完成任务*/
                        finishTaskCondition($orderInfo['member_id'], 3);
                        # 需要进行继续支付
                        return array('status' => true, 'is_continue' => 1, 'msg' => '核销成功,该订单还有未支付的项目,请继续支付', 'pay_money' => $orderPrice);
                    } else {
                        # 核销成功,不需要继续支付
                        $orderCancelStatus = true;
                    }
                } else {
                    if ($cardVoucherInfo['card_type_id'] == 1) {
                        # 查询服务工单是否存在卡券对应的服务并且是已完成未核销的
                        $workOrderInfo = Db::table('order_server')->field('id,price,server_id')
                            ->where(array('server_id' => $cardVoucherInfo['server_id'], 'order_number' => $orderInfo['order_number'], 'status' => 4, 'custommark' => 1))->find();
                    }
                    if ($cardVoucherInfo['card_type_id'] == 3) {
                        # 查询商品工单是否存在卡券对应的商品并且是未核销的
                        $workOrderInfo = Db::table('order_biz')->field('id,biz_pro_id,pro_price,bizpro_number,coupon_price,coupon_number')
                            ->where(array('biz_pro_id' => $cardVoucherInfo['server_id'], 'status' => 2, 'order_number' => $orderInfo['order_number'], 'custommark' => 1))->find();
                    }
                    if (empty($workOrderInfo)) {
                        return array('status' => false, 'msg' => '未查询到工单信息');
                    }
                    if ($cardVoucherInfo['card_type_id'] == 1) {
                        # 修改服务工单状态为已核销
                        $workOrderStatus = Db::table('order_server')->where(array('id' => $workOrderInfo['id']))->update(array('status' => 6, 'coupon_mark' => 2));
                        Db::table('orders')->where(array('order_number' => $this->order['out_trade_no']))->setInc('voucher_price', $workOrderInfo['price']);
                    }
                    if ($cardVoucherInfo['card_type_id'] == 3) {
                        if ($workOrderInfo['bizpro_number'] == 1) {
                            # 已全部核销
                            $couponPrice = floatval(floatval($workOrderInfo['pro_price']) / intval($workOrderInfo['bizpro_number'])) + floatval($workOrderInfo['coupon_price']);
                            # 修改状态为已核销,工单状态为已完成
                            $workOrderStatus = Db::table('order_biz')->where(array('id' => $workOrderInfo['id']))->update(array('status' => 3, 'coupon_mark' => 2));
                        } else {
                            # 计算卡券核销价格(商品总价/商品数量+卡券核销价格)
                            $couponPrice = floatval(($workOrderInfo['pro_price'] / intval($workOrderInfo['bizpro_number']))) + floatval($workOrderInfo['coupon_price']);
                            # 计算该商品使用卡券核销的数量(加1)
                            $couponNumber = intval($workOrderInfo['coupon_number']) + 1;
                            # 判断是否需要将卡券核销状态改为2(已核销)
                            $_couponMark = intval($workOrderInfo['bizpro_number']) - $couponNumber;
                            if ($_couponMark > 0) {
                                # 未核销完
                                # 增加卡券核销数量,卡券核销价格
                                $workOrderStatus = Db::table('order_biz')->where(array('id' => $workOrderInfo['id']))->update(array('coupon_price' => $couponPrice, 'coupon_number' => $couponNumber));
                            } else {
                                # 已全部核销
                                # 增加卡券核销数量,卡券核销价格,修改状态为已核销,工单状态改为已完成
                                $workOrderStatus = Db::table('order_biz')->where(array('id' => $workOrderInfo['id']))->update(array('status' => 3, 'coupon_mark' => 2, 'coupon_price' => $couponPrice, 'coupon_number' => $couponNumber));
                            }
                        }
                        Db::table('orders')->where(array('order_number' => $this->order['out_trade_no']))->setInc('voucher_price', $couponPrice);
                    }
                    if ($workOrderStatus) {
                        if ($cardVoucherInfo['card_type_id'] == 1) {
                            # 服务
                            $voucher_type = 7;
                            $order_type = 2;
                            $cprice = $workOrderInfo['price'];
                        } elseif ($cardVoucherInfo['card_type_id'] == 3) {
                            # 商品
                            $voucher_type = 8;
                            $order_type = 1;
                            $cprice = $couponPrice;
                        }
                        # 添加log_cashcoupon表信息
                        Db::table('log_cashcoupon')->insert(array('voucher_id' => $this->order['voucher_id'], 'member_id' => $orderInfo['member_id'],
                            'create_time' => date("Y-m-d"), 'voucher_price' => $cprice, 'order_number' => $orderInfo['order_number'],
                            'workorder_id' => $workOrderInfo['id'], 'voucher_type' => $voucher_type, 'order_type' => $order_type));
                        # 修改用户卡券状态
                        $memberVoucherStatus = Db::table('member_voucher')->data(array('status' => 2, 'order_id' => $orderInfo['id'], 'order_server_id' => $workOrderInfo['id']))->where(array('id' => $this->order['voucher_id']))->update();
                        if ($memberVoucherStatus) {
                            # 添加卡券使用记录
                            Db::table('log_voucher')->insert(array('member_id' => $orderInfo['member_id'], 'voucher_id' => $this->order['voucher_id'],
                                'status' => 2, 'create_time' => date("Y-m-d H:i:s")));
                            # 判断是否需要进行继续支付,查询工单中待结算的项目
                            $workOrderCountInfo = Db::table('orders o')
                                ->field("o.id,
                            (select count(os.id) from order_server os where os.order_number = o.order_number and os.status = 4) servercount,
                            (select count(ob.id) from order_biz ob where ob.order_number = o.order_number and ob.status = 2) bizcount
                            ")
                                ->where(array('o.order_number' => $orderInfo['order_number']))
                                ->find();
                            $workOrderCount = intval($workOrderCountInfo['servercount']) + intval($workOrderCountInfo['bizcount']);
                            if ($workOrderCount >= 1) {
                                /*完成任务   sp*/
                                finishTaskCondition($orderInfo['member_id'], 3);
                                # 请继续支付
                                return array('status' => true, 'is_continue' => 1, 'msg' => '核销成功,该订单还有未支付的项目，请继续支付');
                            } else {
                                # 核销成功,不需要继续支付
                                $orderCancelStatus = true;
                            }
                        } else {
                            # 用户卡券状态修改失败,将工单状态恢复
                            Db::table('order_server')->where(array('id' => $workOrderInfo['id']))->update(array('status' => 4));
                            return array('status' => false, 'msg' => '核销失败,用户卡券状态修改失败');
                        }
                    } else {
                        # 工单状态修改失败
                        return array('status' => false, 'msg' => '核销失败,工单状态修改失败');
                    }
                }
            }
        }
        if ($orderCancelStatus) {
            # 支付成功
            $this->paySuccess($orderInfo['order_number'], 6, $orderPrice, $ordersType);
        }
        return array('status' => true, 'is_continue' => 0);
    }

    /**
     * @param $orderNumber
     * @param $payType  新 : 1微信 2支付宝  3银联  4现金  5余额  6卡券  7积分
     * @param $payPrice
     * @return array
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     * @content 支付成功
     */
    function paySuccess($orderNumber, $payType, $payPrice, $ordersType = true, $demo = true)
    {
        if (!empty($orderNumber) and !empty($payType)) {
            # 查询订单信息
            $orderInfo = Db::table('orders')->where(array('order_number' => $orderNumber))->find();
            if (empty($orderInfo)) {
                return array('status' => false, 'msg' => '订单信息为空');
            }
            # 抽成 线上订单5%抽成  门店订单 10%抽成 (诚信洗车场(id:692)  不抽成)
            if ($orderInfo['is_online'] == 1) {
                # 线上订单 02-23 17:15
                $drawRatio = 0;
            } else {
                # 门店订单
                $drawRatio = 0.1;
            }
            if ($orderInfo['biz_id'] == 692) {
                $drawRatio = 0;
            }
            # 判断订单是否已经处理过了
            if ($orderInfo['order_status'] != 5 and $orderInfo['order_status'] != 7) {
                if ($payPrice == 0) {
                    $payType = 6;
                }
                if ($payType == 6 or $payType == 5) {
                    $this->countPay($orderInfo['biz_id'], $orderNumber, $orderInfo['member_id'], false, 5);
                }
                # 获取门店信息
                $bizInfo = getsBizInfoArray($orderInfo['biz_id'], 1);
                # 订单id
                $orderId = $orderInfo['id'];
                # 用户id
                $memberId = $orderInfo['member_id'];
                # 当前时间
                $currentTime = date('Y-m-d H:i:s');
                # 结算人员id(门店id , 需要做处理.暂时设置成门店id)----------------------------------------------
                $settlementId = $orderInfo['biz_id'];
                # 将总订单修改为全部完成订单(待打印状态) 7
                if ($bizInfo['biz_type'] == 1) {
                    $orderStatus = 7;
                } else {
                    $orderStatus = 5;
                }
                if ($ordersType) {
                    # 更改支付方式
                    $orderUpdateInfo = array('order_status' => $orderStatus, 'order_over' => $currentTime, 'pay_create' => $currentTime,
                        'pay_price' => $payPrice, 'order_cancel' => 2, 'pay_type' => $payType, 'settlement' => $settlementId);
                } else {
                    # 不需要更改支付方式
                    $orderUpdateInfo = array('order_status' => $orderStatus, 'order_over' => $currentTime, 'pay_create' => $currentTime,
                        'order_cancel' => 2, 'settlement' => $settlementId);
                }

                if ($demo) {
                    Db::table('orders')->where(array('id' => $orderId))
                        ->update($orderUpdateInfo);
                    # 将服务工单修改为已完成订单
                    Db::table('order_server')->where(array('order_number' => $orderNumber))->update(array('status' => 6));
                    # 将商品工单修改为已完成订单
                    Db::table('order_biz')->where(array('order_number' => $orderNumber))->update(array('status' => 3));
                }
                # 查询支付方式
                $payType = Db::table('orders')->field('pay_type')->where(array('order_number' => $orderNumber))->value('pay_type');
                # 增加微信支付宝收款手续费
                if (($payType == 1 or $payType == 2) and $ordersType and $demo and $payPrice > 0) {
                    addExpenses(array("type_id" => 2, "price" => $payPrice * 0.006));
                }
                if ($payType != 6 and $payType != 7 and $payPrice > 0) {
                    $channel = Db::table("channel")->where(array("member_id" => $memberId, "action_type" => 1))->order("id desc")->find();
                    if (!empty($channel)) {
                        if ($channel['channel'] == 10 and $channel['pid'] > 0) {
                            EalspellCommissionService::addMemberConsump($channel['pid'], $payPrice,$memberId,$orderNumber);
                        }
                    }
                }
//                $newMember = Db::table('log_consump')->where(array("member_id" => $memberId))->find();
//                if (empty($newMember)) {
//                    # 查询这个车是不是首次下单
//                    $new_order = Db::table('orders')->where(array('car_liences' => $orderInfo['car_liences']))->where("order_number != '" . $orderNumber . "'")->find();
//                    if (empty($new_order)) {
//                        # 查询这个人在商家有没有订单
//                        $merchant_order = Db::table("merchants_order")->where(array("member_id" => $memberId))->find();
//                        if (empty($merchant_order)) {
//                            # 查询这个人注册是否是代理推荐
//                            $channelInfo = Db::table('channel')->where(array("action_type" => 1, "member_id" => $memberId, "channel" => 10))->find();
//                            if (!empty($channelInfo)) {
//                                EalspellCommissionService::addRegisterCommission($channelInfo['pid'],$memberId);
//                            }
//                        }
//                    }
//                }
                if (!empty($memberId)) {
                    # 添加用户消费记录
                    if ($demo)
                        Db::table('log_consump')->insert(array('member_id' => $memberId, 'consump_price' => $payPrice,
                            'consump_pay_type' => $payType, 'consump_time' => $currentTime, "log_consump_type" => 1, 'biz_id' => $orderInfo['biz_id'],
                            "consump_type" => 2, 'order_number' => $orderNumber, 'income_type' => 1));
                    # 赠送积分
                    # 余额支付不加积分, 门店下单加积分
                    if ($payType != 3 and $orderInfo['is_online'] != 1) {
                        # 加积分
                        Db::table('member_mapping')->where(array('member_id' => $memberId))->setInc('member_integral', intval($payPrice));
                        # 加积分记录(积分来源=>门店购买服务(小程序))
                        Db::table('log_integral')->insert(array(
                            'integral_number' => intval($payPrice),
                            'integral_source' => -3,
                            'member_id' => $memberId,
                            'integral_type' => 1,
                            'integral_time' => $currentTime
                        ));
                        # 添加市场补贴记录
                        Db::table('subsidy')->insert(array(
                            'subsidy_type' => 2,
                            'subsidy_come' => 1,
                            'subsidy_create' => $currentTime,
                            'subsidy_number' => intval($payPrice)
                        ));
                    }
                    # 添加用户到店记录
                    if ($demo) {
                        Db::table('biz_traffic')->insert(array(
                            'member_id' => $memberId,
                            'biz_id' => $orderInfo['biz_id'],
                            'create_time' => $currentTime,
                            'type' => 1,
                            'pid' => $orderId,
                            'amount' => $payPrice,
                            'member_car_id' => $orderInfo['member_car_id'],
                            'pay_type' => $payType,
                        ));
                    }
                }
                ###############################
                # 定义订单总价格
                $setOrderCount = 0;
                # 定义结算金额
                $settlementPrice = 0;
                # 定义抽成金额
                $commissionPrice = 0;
                # 定义补贴金额
                $subsidyCount = 0;
                # 定义票机数组
                $printer_info = array();
                # 定义票机详情数组
                $print_detaill = array();
                # 提成信息数组
                $deductArr = array();
                # 定义评论信息数组
                $evealuationArr = array();
                # 定义员工超时扣款数据数组
                $timeoutArr = array();
                # 定义服务记录数组
                $logServiceArr = array();
                # 定义门店收入数组
                $bizIncomeArr = array();
                # 质保信息记录
                $warrantyArr = array();
                # 保养信息记录
                $maintainArr = array();
                # 维修信息记录
                $repairArr = array();
                # 查询服务工单
                $orderServer = Db::table('order_server os')
                    ->field('id,server_id,price,custommark,coupon_mark,server_id,employee_id,referrer,station_id,original_price,
                if(custommark=1,(select service_title from service where id =os.server_id),
                (select custom_server_title from customserver where id=os.server_id)) serviceTitle,
                if(custommark=1,(select is_warranty from service where id =os.server_id),2) is_warranty,
                if(custommark=1,(select is_repair from service where id =os.server_id),2) is_repair,
                if(custommark=1,(select is_maintain from service where id =os.server_id),2) is_maintain,
                if(custommark=1,(select biz_pid from service where id =os.server_id),1) biz_pid,
                if(custommark=1,(select relation_eva from service where id =os.server_id),2) relation_eva,
                if(custommark=2,(select log_type from customserver where id =os.server_id),0) log_type
                ')
                    ->where(array('order_number' => $orderNumber))->select();
                # 查询商品工单
                $orderBiz = Db::table('order_biz')->field('id,biz_pro_id,pro_price,custommark,coupon_mark,original_pro_price,
            employee_id,referrer,bizpro_number,coupon_price,coupon_number,station_id,pro_price price')
                    ->where(array('order_number' => $orderNumber))->select();

                # 员工提成比率--中评
                $commission_medium = config('ecarcoo.comment_rate_commission')['medium'];
//                if ($bizInfo['biz_type'] != 1) {
//                    $commission_medium = 1;
//                }
                # 结算比率--中评
                $settlement_medium = config('ecarcoo.comment_rate_settlement')['medium'];
                $commissionService = new CommissionService();
                # 遍历服务工单
                if (!empty($orderServer)) {
                    foreach ($orderServer as $k => $v) {
                        $settlement_service_info = 0;
                        $settlement_service = 0;
                        # 平台承担金额
                        $platform_price = 0;
//                        $platform_price_mark = true;
                        $withdrawal_amount = 0;
                        # 是否使用了单独服务现金抵值券
                        $coupon = 0;
                        # 服务员工id集合整理成数组
                        if (!empty($v['employee_id'])) {
                            $employeeIdArr = explode(',', $v['employee_id']);
                        } else {
                            $employeeIdArr = array();
                        }
                        # 推荐员工id集合整理成数组
                        if (!empty($v['referrer'])) {
                            $referereIdArr = explode(',', $v['referrer']);
                        } else {
                            $referereIdArr = array();
                        }
                        if ($bizInfo['biz_type'] == 1) {
                            $commissionService->commission($orderInfo['biz_id'], $v['id'], 1, $orderInfo['car_level'], 'add');
                        }
                        if ($bizInfo['biz_type'] == 3 or $bizInfo['biz_type'] == 2) {
                            # 查询该服务该门店下的结算价格
                            # 判断是否使用了卡券支付(判断卡券的结算金额)
                            $memberVoucherInfo = Db::table('member_voucher')->field('id,settlement_price,voucher_cost,voucher_type,voucher_id,voucher_source')
//                                ->where("id = (select voucher_id from log_cashcoupon where order_number = '" . $orderNumber . "' and workorder_id = " . $v['id'] . " limit 1)")
                                ->where("order_id = " . $orderInfo['id'] . " and order_server_id = " . $v['id'])
                                ->find();
                            if ($v['custommark'] == 1) {
                                if (!empty($memberVoucherInfo)) {
                                    $settlement_service_info = $memberVoucherInfo['settlement_price'];
                                    $coupon = $memberVoucherInfo['voucher_cost'];
                                    if (!empty($settlement_service_info)) {
//                                        $platform_price_mark = false;
                                        $settlement_service_info = json_decode($settlement_service_info, true);
                                        $settlement_service_info = $settlement_service_info[$orderInfo['car_level']];
                                        Db::table('order_server')->where(array('id' => $v['id']))->update(array('settlement_type' => 2));
                                    }
                                    if ($demo) {
                                        # 增加补贴记录,12,卡券核销或抵用
                                        addSubsidy(array("subsidy_type" => 12, "subsidy_number" => $memberVoucherInfo['voucher_cost'], 'member_id' => $memberId, "biz_id" => $orderInfo['biz_id'], 'voucher_id' => $memberVoucherInfo['id'], 'order_number' => $orderNumber, 'order_type' => 2, 'pid' => $v['id']));
                                    }
                                }
                                if (empty($settlement_service_info)) {
                                    # 系统服务
                                    $settlement_service_info = Db::table('service_car_mediscount')->field('settlement_amount')
                                        ->where(array('biz_id' => $orderInfo['biz_id'], 'service_id' => $v['server_id'], 'service_type' => 1, 'car_level_id' => $orderInfo['car_level']))
                                        ->value('settlement_amount');
                                    if (empty($settlement_service_info)) {
                                        if ($v['biz_pid'] != 0) {
                                            $settlement_service_info = $v['price'];
                                        }
                                    } else {
//                                        $platform_price_mark = false;
                                    }
                                }
                            } else {
                                # 自定义服务
                                $settlement_service_info = $v['price'];
                            }
                            # 判断平台承担比例
                            if (!empty($memberVoucherInfo)) {
                                if ($memberVoucherInfo['voucher_type'] >= 11 and $memberVoucherInfo['voucher_type'] <= 16) {
                                    $platformRatio = Db::table('merchants_voucher')
                                        ->where(array('id' => $memberVoucherInfo['voucher_id']))
                                        ->value('platform_ratio');
                                    if (!empty($platformRatio)) {
                                        if ($v['biz_pid'] > 0) {
                                            # 门店服务
                                            $platform_price = ($memberVoucherInfo['voucher_cost'] * $platformRatio);
                                        } else {
                                            # 线上服务
                                            $platform_price = -($memberVoucherInfo['voucher_cost'] * (1 - $platformRatio));
                                        }
                                    } else {
                                        if ($memberVoucherInfo['voucher_source'] != 14) {
                                            # 不是积分兑换卡券  合作端承担50%
                                            if ($v['biz_pid'] > 0) {
                                                # 门店服务
                                                $platform_price = ($memberVoucherInfo['voucher_cost'] * 0.5);;
                                            } else {
                                                # 线上服务
                                                $platform_price = -($memberVoucherInfo['voucher_cost'] * 0.5);;
                                            }
                                        } else {
                                            # 门店全部承担
                                            if ($v['biz_pid'] > 0) {
                                                # 门店服务
                                                $platform_price = ($memberVoucherInfo['voucher_cost']);
                                            } else {
                                                # 线上服务
                                                $platform_price = 0;
                                            }
                                        }
                                    }
                                }
                            }
                            # 该服务使用卡券核销掉了,按门店服务设置的结算价格
                            if ($v['coupon_mark'] == 2) {
                                $setOrderCount += $v['price'];
                                settleService:
                                # 应结算价格  $settlement_medium
//                                $settlement_service_info = $v['price'];
//                                if ($bizInfo['settlement_method'] == 2) {
//                                    # 按订单价格结算
//                                    $settlement_service_info = $v['price'];
//                                }
//                                if ($payType == 3 or $payType == 4) {
//                                    #现金和银联  结算价格=卡券金额
//                                    $settlement_service_info = $coupon;
//                                }
                                # 加上平台承担的卡券金额
//                                if ($platform_price_mark)
                                $settlement_service_info += $platform_price;
                                $should_settle = $settlement_service_info;
                                # 抽成金额
                                if ($v['custommark'] == 1) {
                                    # 系统服务
                                    # 服务提成
                                    $service_commission = $settlement_service_info * $bizInfo['commission_platservice'] * $commission_medium;
                                    # 推荐提成
                                    $recommended_ommission = $settlement_service_info * $bizInfo['recommond_commission_platservice'];
                                    # 抽成 线上订单5%抽成  门店订单 10%抽成
//                                    $withdrawal_amount = $should_settle * $bizInfo['extract_platservice'];
                                    $withdrawal_amount = $should_settle * $drawRatio;
                                } else {
                                    # 自定义服务
                                    # 服务提成
                                    $service_commission = $settlement_service_info * $bizInfo['commission_selfservice'] * $commission_medium;
                                    # 推荐提成
                                    $recommended_ommission = $settlement_service_info * $bizInfo['recommond_commission_selfservice'];
//                                    $withdrawal_amount = $should_settle * $bizInfo['extract_selfservice'];
                                    $withdrawal_amount = $should_settle * $drawRatio;
                                }
                                # 实际结算价格
                                $settlementPrice += $should_settle - $withdrawal_amount;
                                $settlement_service = $should_settle - $withdrawal_amount;
                                # 实际抽成金额
                                $commissionPrice += $withdrawal_amount;
                                # 记录结算,计算提成时要使用的价格
                                Db::table('order_server')->where(array('id' => $v['id']))->update(array('price_settlement' => $settlement_service_info));
                            } else {
                                if ($payType == 5) {
                                    # 余额支付,
                                    goto settleService;
                                } elseif ($payType == 1 or $payType == 2) {
                                    # 微信支付/支付宝支付27.2 1.36  25.84
                                    # 应结算价格 $settlement_medium
//                                    $should_settle = $v['original_price'];
                                    if ($bizInfo['settlement_method'] == 2) {
                                        # 按订单价格结算
                                        $settlement_service_info = $v['original_price'];
                                    }
                                    # 加上平台承担的卡券金额
//                                    if ($platform_price_mark)
                                    $settlement_service_info += $platform_price;
                                    $should_settle = $settlement_service_info;
                                    $setOrderCount += $v['original_price'];
                                    # 抽成金额
                                    if ($v['custommark'] == 1) {
                                        # 系统服务
                                        # 服务提成
                                        $service_commission = $v['original_price'] * $bizInfo['commission_platservice'] * $commission_medium;
                                        # 推荐提成
                                        $recommended_ommission = $v['original_price'] * $bizInfo['recommond_commission_platservice'];
//                                        $withdrawal_amount = $should_settle * $bizInfo['extract_platservice'];
                                        $withdrawal_amount = $should_settle * $drawRatio;
                                    } else {
                                        # 自定义服务
                                        # 服务提成
                                        $service_commission = $v['original_price'] * $bizInfo['commission_selfservice'] * $commission_medium;
                                        # 推荐提成
                                        $recommended_ommission = $v['original_price'] * $bizInfo['recommond_commission_selfservice'];
//                                        $withdrawal_amount = $should_settle * $bizInfo['extract_selfservice'];
                                        $withdrawal_amount = $should_settle * $drawRatio;
                                    }
                                    # 实际结算价格
                                    $settlementPrice += $should_settle - $withdrawal_amount;
                                    $settlement_service = $should_settle - $withdrawal_amount;
                                    # 实际抽成金额
                                    $commissionPrice += $withdrawal_amount;
                                    # 记录结算,计算提成时要使用的价格  $v['original_price']
                                    Db::table('order_server')->where(array('id' => $v['id']))->update(array('price_settlement' => $settlement_service_info));
                                } else {
                                    $setOrderCount += $v['original_price'];
                                    /*
                                     # 其他方式支付 , 银联/现金
                                    # 应结算价格 $settlement_medium
//                                    $should_settle = $v['original_price'];
                                    $should_settle = $settlement_service_info;*/
                                    # 抽成金额
                                    if ($v['custommark'] == 1) {
                                        # 系统服务
                                        # 服务提成
                                        $service_commission = $v['original_price'] * $bizInfo['commission_platservice'] * $commission_medium;
                                        # 推荐提成
                                        $recommended_ommission = $v['original_price'] * $bizInfo['recommond_commission_platservice'];
//                                        $withdrawal_amount = $should_settle * $bizInfo['extract_platservice'];
                                    } else {
                                        # 自定义服务
                                        # 服务提成
                                        $service_commission = $v['original_price'] * $bizInfo['commission_selfservice'] * $commission_medium;
                                        # 推荐提成
                                        $recommended_ommission = $v['original_price'] * $bizInfo['recommond_commission_selfservice'];
//                                        $withdrawal_amount = $should_settle * $bizInfo['extract_selfservice'];
                                    }
                                    # 实际结算价格
                                    /*$settlementPrice += (($should_settle - $withdrawal_amount) - $v['original_price']);
                                    $settlement_service = (($should_settle - $withdrawal_amount) - $v['original_price']);
                                    # 实际抽成金额
                                    $commissionPrice += $withdrawal_amount;

                                    # 记录结算,计算提成时要使用的价格  $v['original_price']
                                    Db::table('order_server')->where(array('id' => $v['id']))->update(array('price_settlement' => $settlement_service_info));
                                    */
                                }
                            }
                            if ($v['custommark'] == 1) {
                                # 系统服务,最终结算价格
//                                if ($v['relation_eva'] == 1) {
//                                    # 该服务 关联用户评价
//                                    $final_settlement = $settlement_service * $settlement_medium;
//                                } else {
//                                    # 不关联
//                                    $final_settlement = $settlement_service;
//                                }
                                if (false) {//$bizInfo['relevant_evaluation'] == 1
                                    # 门店设置里面关联评价
                                    $final_settlement = $settlement_service * $settlement_medium;
                                } else {
                                    # 门店设置  不 关联评价
                                    $final_settlement = $settlement_service;
                                }
                            } else {
                                # 自定义服务
                                $final_settlement = $settlement_service;
                            }
                            # 修改最终结算价格
                            Db::table('order_server')->where(array('id' => $v['id']))->update(array('final_settlement' => $final_settlement));
                        }
                        # 服务人员添加提成
                        if (!empty($employeeIdArr)) {
                            # 超时时间
                            $overtime_diff = 0;
                            $overtime_price = 0;
                            /* # 查询是否超时
                             $timeout = Db::table("log_order_timeout")->where(array(
                                 "order_number" => $orderNumber,
                                 "order_server_id" => $v['id'],
                                 "iscut" => 1
                             ))->find();
                             if (!empty($timeout)) {
                                 # 查询该服务每分钟扣款多少钱
                                 $overtime_price = Db::table('service_class sc')
                                     ->field('sc.service_outtime')
                                     ->where("sc.id = (select s.service_class_id from service s where s.id=" . $v['server_id'] . ")")
                                     ->find()['service_outtime'];
                                 if ($overtime_price != 0) {
                                     # 计算工单超时时间
                                     $overtime_diff = floor((strtotime($timeout['order_over']) - strtotime($timeout['order_endtime'])) % 86400 / 60);
                                 }
                             }*/
                            foreach ($employeeIdArr as $eid) {
                                if (!empty($eid)) {
                                    if ($bizInfo['biz_type'] == 3 or $bizInfo['biz_type'] == 2) {
                                        # 合作门店
                                        # 添加提成数组信息(服务提成)
                                        array_push($deductArr, array(
                                            "order_number" => $orderNumber,
                                            'order_server_id' => $v['id'],
                                            'type' => 2,
                                            'biz_id' => $orderInfo['biz_id'],
                                            'employee_id' => $eid,
                                            'deduct' => getsPriceFormat($service_commission / count($employeeIdArr)),
                                            'create' => $currentTime,
                                            "refer_mark" => 1,
                                            "exec_update" => 1,
                                        ));
                                    } else {
                                        # 直营店
                                        /* if ($overtime_diff > 0) {
                                             # 超时扣款
                                             array_push($deductArr, array(
                                                 'order_number' => $orderNumber,
                                                 'order_server_id' => $v['id'],
                                                 'type' => 2,
                                                 'biz_id' => $orderInfo['biz_id'],
                                                 'employee_id' => $eid,
                                                 'deduct' => -(floatval($overtime_price) * $overtime_diff),
                                                 "refer_mark" => 1,
                                                 "exec_update" => 0,
                                             ));
                                         }*/
//                                        else {
                                        # 没超时,正常计算提成
//                                        getsDeduct(count($employeeIdArr), $orderNumber, $v['id'], 2, $eid, 1, 4, $v['station_id']);
//                                        }
                                    }
                                    # 添加评论信息数组(默认中评,用户评论之后在进行修改)
                                    array_push($evealuationArr,
                                        array('order_id' => $orderId,
                                            'biz_id' => $orderInfo['biz_id'],
                                            'employee_id' => $eid,
                                            'create_time' => $currentTime,
                                            'score' => 3,
                                            'evalua_level' => 3,
                                            'reffermark' => 1,
                                            'orderserver_id' => $v['id'],
                                            'type' => 1));
                                }
                            }
                        } else {
                            array_push($evealuationArr,
                                array('order_id' => $orderId,
                                    'biz_id' => $orderInfo['biz_id'],
                                    'employee_id' => 0,
                                    'create_time' => $currentTime,
                                    'score' => 3,
                                    'evalua_level' => 3,
                                    'reffermark' => 1,
                                    'orderserver_id' => $v['id'],
                                    'type' => 1));
                        }
                        # 推荐人员加提成
                        if (!empty($referereIdArr)) {
                            foreach ($referereIdArr as $rid) {
                                if (!empty($rid)) {
                                    if ($bizInfo['biz_type'] == 3 or $bizInfo['biz_type'] == 2) {
                                        # 合作店
                                        # 添加提成数组信息(推荐提成)
                                        array_push($deductArr, array(
                                            "order_number" => $orderNumber,
                                            'order_server_id' => $v['id'],
                                            'type' => 2,
                                            'biz_id' => $orderInfo['biz_id'],
                                            'employee_id' => $rid,
                                            'deduct' => getsPriceFormat($recommended_ommission / count($referereIdArr)),
                                            'create' => $currentTime,
                                            "refer_mark" => 2,
                                            "exec_update" => 0,
                                        ));
                                    } else {
                                        # 直营店
                                        // getsReferrerDeduct(count($referereIdArr), $orderNumber, $v['id'], 2, $rid, 1, 4, $v['station_id']);
                                    }
                                }
                            }
                        }
                        # 添加服务记录数据信息
                        array_push($logServiceArr, array(
                            'member_id' => $memberId,
                            'log_service_source' => $v['serviceTitle'],
                            'log_service_price' => $v['price'],
                            'log_service_create' => $currentTime,
                            'biz_id' => $orderInfo['biz_id'],
                            'pay_type' => $payType,
                            'order_number' => $orderNumber,
                            'car_mileage' => $orderInfo['car_mileages'],
                            'car_licens' => $orderInfo['car_liences'],
                            'station_id' => $v['station_id'],
                            'order_id' => $v['id'],
                        ));
                        # 服务次数加一
                        Db::table('service')->where(array('id' => $v['server_id']))->setInc('real_num');
                        # 系统服务减库存
                        if ($v['custommark'] == 1) {
                            $this->serviceInventDec($v['server_id'], $orderInfo['biz_id']);
                        }
                        # 添加门店收入记录数据信息
//                        if ($payType != 3) {
                        if ($v['coupon_mark'] != 2) {
                            array_push($bizIncomeArr, array(
                                'biz_id' => $orderInfo['biz_id'],
                                'biz_income' => $v['price'],
                                'pay_type' => $payType,
                                'pay_create' => $currentTime,
                                'member_id' => $memberId,
                                'income_type' => 1,
                                'pid' => $v['server_id'],
                                'pay_year' => date('Y'),
                                'pay_month' => date('m'),
                                'pay_day' => date('d'),
                                'custommark' => $v['custommark'],
                                'order_number' => $orderNumber
                            ));
                        }
//                        }
                        # 判断该服务是否关联质保记录
                        if ($v['is_warranty'] == 1) {
                            # 查询质保信息
                            $warrantyInfo = Db::table('service_log')->where(array('service_id' => $v['server_id'], 'log_type' => 3))->find();
                            if (!empty($warrantyInfo)) {
                                # 添加质保记录
                                array_push($warrantyArr, array(
                                    'member_id' => $memberId,
                                    'car_num' => $orderInfo['car_liences'],
                                    'biz_id' => $orderInfo['biz_id'],
                                    'order_number' => $orderNumber,
                                    'warranty_id' => $warrantyInfo['id'],
                                    'now_mileage' => $orderInfo['car_mileages'],
                                    'now_time' => $currentTime,
                                    'next_mileage' => $orderInfo['car_mileages'] + $warrantyInfo['log_kilometers'],
                                    'next_time' => date('Y-m-d H:i:s', strtotime('+ ' . intval($warrantyInfo['log_validity']) . ' days', strtotime($currentTime))),
                                    'custommark' => 1,
                                ));
                            }
                        }
                        # 判断该服务是否关联保养记录
                        if ($v['is_maintain'] == 1) {
                            # 查询保养信息
                            $maintainInfo = Db::table('service_log')->where(array('service_id' => $v['server_id'], 'log_type' => 1))->find();
                            if (!empty($maintainInfo)) {
                                array_push($maintainArr, array(
                                    'car_licens' => $orderInfo['car_liences'],
                                    'maintain_type' => -$maintainInfo['id'],
                                    'maintain_price' => $v['price'],
                                    'now_mileage' => $orderInfo['car_mileages'],
                                    'next_mileage' => $orderInfo['car_mileages'] + $maintainInfo['log_kilometers'],
                                    'maintain_time' => $currentTime,
                                    'suggest_time' => date('Y-m-d H:i:s', strtotime('+ ' . intval($maintainInfo['log_validity']) . ' days', strtotime($currentTime))),
                                    'biz_id' => $orderInfo['biz_id'],
                                    'maintain_title' => $maintainInfo['log_title'],
                                    'custommark' => 1,

                                ));
                            }
                        }
                        # 判断该服务是否关联维修记录
                        if ($v['is_repair'] == 1) {
                            # 查询保养信息
                            $maintainInfo = Db::table('service_log')->where(array('service_id' => $v['server_id'], 'log_type' => 2))->find();
                            if (!empty($maintainInfo)) {
                                array_push($repairArr, array(
                                    'member_id' => $memberId,
                                    'car_num' => $orderInfo['car_liences'],
                                    'now_mil' => $orderInfo['car_mileages'],
                                    'repair_title' => $maintainInfo['log_title'],
                                    'b_id' => $orderInfo['biz_id'],
                                    'add_time' => $currentTime,
                                ));
                            }
                        }

                        if ($v['custommark'] == 2 and $v['log_type'] > 0) {
                            $customservices = Db::table("customserver")->where(array("id" => $v['server_id']))->find();
                            if (!empty($customservices)) {
                                if ($v['log_type'] == 1) {
                                    # 关联保养记录
                                    array_push($maintainArr, array(
                                        'car_licens' => $orderInfo['car_liences'],
                                        'maintain_type' => -$customservices['id'],
                                        'maintain_price' => $v['price'],
                                        'now_mileage' => $orderInfo['car_mileages'],
                                        'next_mileage' => $orderInfo['car_mileages'] + $customservices['log_kilometers'],
                                        'maintain_time' => $currentTime,
                                        'suggest_time' => date('Y-m-d H:i:s', strtotime('+ ' . intval($customservices['log_validity']) . ' days', strtotime($currentTime))),
                                        'biz_id' => $orderInfo['biz_id'],
                                        'maintain_title' => $customservices['custom_server_title'],
                                        'custommark' => 2,
                                    ));
                                } elseif ($v['log_type'] == 2) {
                                    array_push($repairArr, array(
                                        'member_id' => $memberId,
                                        'car_num' => $orderInfo['car_liences'],
                                        'now_mil' => $orderInfo['car_mileages'],
                                        'repair_title' => $customservices['log_title'],
                                        'b_id' => $orderInfo['biz_id'],
                                        'add_time' => $currentTime,
                                    ));
                                } else {
                                    # 添加质保记录
                                    array_push($warrantyArr, array(
                                        'member_id' => $memberId,
                                        'car_num' => $orderInfo['car_liences'],
                                        'biz_id' => $orderInfo['biz_id'],
                                        'order_number' => $orderNumber,
                                        'warranty_id' => $customservices['id'],
                                        'now_mileage' => $orderInfo['car_mileages'],
                                        'now_time' => $currentTime,
                                        'next_mileage' => $orderInfo['car_mileages'] + $customservices['log_kilometers'],
                                        'next_time' => date('Y-m-d H:i:s', strtotime('+ ' . intval($customservices['log_validity']) . ' days', strtotime($currentTime))),
                                        'custommark' => 2,
                                    ));
                                }
                            }
                        }
                    }
                }
                # 遍历商品工单
                if (!empty($orderBiz)) {
                    foreach ($orderBiz as $k => $v) {
                        $settlement_order = 0;
                        # 服务员工id集合整理成数组
                        if (!empty($v['employee_id'])) {
                            $employeeIdArr = explode(',', $v['employee_id']);
                        } else {
                            $employeeIdArr = array();
                        }
                        # 推荐员工id集合整理成数组
                        if (!empty($v['referrer'])) {
                            $referereIdArr = explode(',', $v['referrer']);
                        } else {
                            $referereIdArr = array();
                        }
                        if ($bizInfo['biz_type'] == 1) {
                            $commissionService->commission($orderInfo['biz_id'], $v['id'], 2, $orderInfo['car_level'], 'add');
                        }
                        if ($bizInfo['biz_type'] == 3 or $bizInfo['biz_type'] == 2) {
                            # 加盟店(计算门店抽成,)
                            # 记录结算,计算提成时要使用的价格
                            Db::table('order_biz')->where(array('id' => $v['id']))->update(array('price_settlement' => $v['pro_price']));
                            if ($payType == 3 or $payType == 4) {
                                $setOrderCount += $v['original_pro_price'];
                                if ($v['coupon_mark'] == 2) {
                                    $memberVoucherInfo = Db::table('member_voucher')->field('settlement_price,voucher_cost')
                                        ->where("id = (select voucher_id from log_cashcoupon where order_number = '" . $orderNumber . "' and workorder_id = " . $v['id'] . " and order_type = 1 limit 1)")
                                        ->find();
                                    if (!empty($memberVoucherInfo)) {
                                        # 应结算价格
                                        $should_settle = $memberVoucherInfo['voucher_cost'];
                                        # 增加补贴记录,12,卡券核销或抵用
                                        addSubsidy(array("subsidy_type" => 12, "subsidy_number" => $memberVoucherInfo['voucher_cost'], 'member_id' => $memberId, "biz_id" => $orderInfo['biz_id'], 'voucher_id' => $memberVoucherInfo['id'], 'order_number' => $orderNumber, 'order_type' => 1, 'pid' => $v['id']));
                                        # 抽成金额
                                        if ($v['custommark'] == 1) {
                                            # 系统商品
                                            # 服务提成
                                            $service_commission = $should_settle * $bizInfo['commission_platpro'] * $commission_medium;
                                            # 推荐提成
                                            $recommended_ommission = $should_settle * $bizInfo['recommond_commission_platpro'];
                                            # 抽成
//                                            $withdrawal_amount = $should_settle * $bizInfo['proportion'];
                                            $withdrawal_amount = $should_settle * $drawRatio;
                                        } else {
                                            # 自定义商品
                                            # 服务提成
                                            $service_commission = $should_settle * $bizInfo['commission_selfpro'] * $commission_medium;
                                            # 推荐提成
                                            $recommended_ommission = $should_settle * $bizInfo['recommond_commission_selfpro'];
                                            # 抽成
//                                            $withdrawal_amount = $should_settle * $bizInfo['extract_selfpro'];
                                            $withdrawal_amount = $should_settle * $drawRatio;
                                        }
                                        # 实际抽成金额
                                        $commissionPrice += $withdrawal_amount;
                                        # 其他方式支付 , 银联/现金
                                        # 实际结算价格
                                        $settlementPrice += (($should_settle - $withdrawal_amount) - $should_settle);
                                        $settlement_order = (($should_settle - $withdrawal_amount) - $should_settle);
                                    }
                                }
                            } elseif ($payType == 5) {
                                $setOrderCount += $v['pro_price'];
                                $should_settle = $v['pro_price'];
                                # 抽成金额
                                if ($v['custommark'] == 1) {
                                    # 系统商品
                                    # 服务提成
                                    $service_commission = $should_settle * $bizInfo['commission_platpro'] * $commission_medium;
                                    # 推荐提成
                                    $recommended_ommission = $should_settle * $bizInfo['recommond_commission_platpro'];
//                                    $withdrawal_amount = $should_settle * $bizInfo['proportion'];
                                    $withdrawal_amount = $should_settle * $drawRatio;
                                } else {
                                    # 自定义商品
                                    # 服务提成
                                    $service_commission = $should_settle * $bizInfo['commission_selfpro'] * $commission_medium;
                                    # 推荐提成
                                    $recommended_ommission = $should_settle * $bizInfo['recommond_commission_selfpro'];
//                                    $withdrawal_amount = $should_settle * $bizInfo['extract_selfpro'];
                                    $withdrawal_amount = $should_settle * $drawRatio;
                                }
                                # 实际抽成金额
                                $commissionPrice += $withdrawal_amount;
                                $settlementPrice += $should_settle - $withdrawal_amount;
                                $settlement_order = $should_settle - $withdrawal_amount;
                            } else {
                                # 微信支付/支付宝支付
                                # 实际结算价格
                                $setOrderCount += $v['original_pro_price'];
                                $should_settle = $v['original_pro_price'];
                                if ($bizInfo['settlement_method'] == 2) {
                                    # 按订单价格结算
                                    $should_settle = $v['pro_price'];
                                }
                                # 抽成金额
                                if ($v['custommark'] == 1) {
                                    # 系统商品
                                    # 服务提成
                                    $service_commission = $should_settle * $bizInfo['commission_platpro'] * $commission_medium;
                                    # 推荐提成
                                    $recommended_ommission = $should_settle * $bizInfo['recommond_commission_platpro'];
//                                    $withdrawal_amount = $should_settle * $bizInfo['proportion'];
                                    $withdrawal_amount = $should_settle * $drawRatio;
                                } else {
                                    # 自定义商品
                                    # 服务提成
                                    $service_commission = $should_settle * $bizInfo['commission_selfpro'] * $commission_medium;
                                    # 推荐提成
                                    $recommended_ommission = $should_settle * $bizInfo['recommond_commission_selfpro'];
//                                    $withdrawal_amount = $should_settle * $bizInfo['custom_pro_royalty'];
                                    $withdrawal_amount = $should_settle * $drawRatio;
                                }
                                # 实际抽成金额
                                $commissionPrice += $withdrawal_amount;
                                $settlementPrice += $should_settle - $withdrawal_amount;
                                $settlement_order = $should_settle - $withdrawal_amount;
                            }
                            # 修改最终结算价格
                            if ($v['custommark'] == 1) {
                                # 系统商品,最终结算价格
                                $final_settlement = $settlement_order * $settlement_medium;
                            } else {
                                # 自定义商品
                                $final_settlement = $settlement_order;
                            }
                            Db::table('order_biz')->where(array('id' => $v['id']))->update(array('final_settlement' => $final_settlement, 'price_settlement' => $should_settle));
                        }
                        # 加订单总金额
//                        $setOrderCount += floatval($v['pro_price']);
                        # 服务人员加提成
                        if (!empty($employeeIdArr)) {
                            foreach ($employeeIdArr as $eid) {
                                if (!empty($eid)) {
                                    if ($bizInfo['biz_type'] == 3 or $bizInfo['biz_type'] == 2) {
                                        # 合作店
                                        # 添加提成数组信息(服务提成)
                                        array_push($deductArr, array(
                                            "order_number" => $orderNumber,
                                            'order_server_id' => $v['id'],
                                            'type' => 1,
                                            'biz_id' => $orderInfo['biz_id'],
                                            'employee_id' => $eid,
                                            'deduct' => getsPriceFormat($service_commission / count($employeeIdArr)),
                                            'create' => $currentTime,
                                            "refer_mark" => 1,
                                            "exec_update" => 1,
                                        ));
                                    } else {
                                        # 直营店
//                                        getsDeduct(count($employeeIdArr), $orderNumber, $v['id'], 1, $eid, 1, 4, $v['station_id']);
                                        //$commissionService->commission($orderInfo['biz_id'],$v['id'],2,$orderInfo['car_level'],'add',$eid,3);
                                    }
                                    # 添加评论信息(默认中评)(用户评论之后再进行修改)
                                    array_push($evealuationArr,
                                        array('order_id' => $orderId,
                                            'biz_id' => $orderInfo['biz_id'],
                                            'employee_id' => $eid,
                                            'create_time' => $currentTime,
                                            'score' => 3,
                                            'evalua_level' => 3,
                                            'reffermark' => 1,
                                            'orderserver_id' => $v['id'],
                                            'type' => 2));
                                }
                            }
                        } else {
                            array_push($evealuationArr,
                                array('order_id' => $orderId,
                                    'biz_id' => $orderInfo['biz_id'],
                                    'employee_id' => 0,
                                    'create_time' => $currentTime,
                                    'score' => 3,
                                    'evalua_level' => 3,
                                    'reffermark' => 1,
                                    'orderserver_id' => $v['id'],
                                    'type' => 2));
                        }
                        # 推荐人员加提成
                        if (!empty($referereIdArr)) {
                            foreach ($referereIdArr as $rid) {
                                if (!empty($rid)) {
                                    if ($bizInfo['biz_type'] == 3 or $bizInfo['biz_type'] == 2) {
                                        # 合作店
                                        # 添加提成数组信息(服务提成)
                                        array_push($deductArr, array(
                                            "order_number" => $orderNumber,
                                            'order_server_id' => $v['id'],
                                            'type' => 1,
                                            'biz_id' => $orderInfo['biz_id'],
                                            'employee_id' => $rid,
                                            'deduct' => getsPriceFormat($recommended_ommission / count($referereIdArr)),
                                            'create' => $currentTime,
                                            "refer_mark" => 2,
                                            "exec_update" => 0,
                                        ));
                                    } else {
                                        # 直营店
                                        // getsReferrerDeduct(count($referereIdArr), $orderNumber, $v['id'], 1, $rid, 1, 4, $v['station_id']);
                                    }
                                }
                            }
                        }
                        # 减库存
                        if ($v['custommark'] == 1) {
                            Db::table('biz_invent')->where(array('biz_pro_id' => $v['biz_pro_id'], 'biz_id' => $orderInfo['biz_id']))
                                ->setDec('number', $v['bizpro_number']);
                        } else {
                            # 查询是否需要生成记录
                            $customPro = Db::table("custom_biz")->where(array("id" => $v['biz_pro_id']))->find();
                            if (!empty($customPro) and $customPro['log_type'] > 0) {
                                if ($customPro['log_type'] == 1) {
                                    # 关联保养记录
                                    array_push($maintainArr, array(
                                        'car_licens' => $orderInfo['car_liences'],
                                        'maintain_type' => -$customPro['id'],
                                        'maintain_price' => $v['price'],
                                        'now_mileage' => $orderInfo['car_mileages'],
                                        'next_mileage' => $orderInfo['car_mileages'] + $customPro['log_kilometers'],
                                        'maintain_time' => $currentTime,
                                        'suggest_time' => date('Y-m-d H:i:s', strtotime('+ ' . intval($customPro['log_validity']) . ' days', strtotime($currentTime))),
                                        'biz_id' => $orderInfo['biz_id'],
                                        'maintain_title' => $customPro['custom_biz_title'],
                                        'custommark' => 3,
                                    ));
                                } elseif ($customPro['log_type'] == 2) {
                                    array_push($repairArr, array(
                                        'member_id' => $memberId,
                                        'car_num' => $orderInfo['car_liences'],
                                        'now_mil' => $orderInfo['car_mileages'],
                                        'repair_title' => $customPro['log_title'],
                                        'b_id' => $orderInfo['biz_id'],
                                        'add_time' => $currentTime,
                                    ));
                                } else {
                                    # 添加质保记录
                                    array_push($warrantyArr, array(
                                        'member_id' => $memberId,
                                        'car_num' => $orderInfo['car_liences'],
                                        'biz_id' => $orderInfo['biz_id'],
                                        'order_number' => $orderNumber,
                                        'warranty_id' => $customPro['id'],
                                        'now_mileage' => $orderInfo['car_mileages'],
                                        'now_time' => $currentTime,
                                        'next_mileage' => $orderInfo['car_mileages'] + $customPro['log_kilometers'],
                                        'next_time' => date('Y-m-d H:i:s', strtotime('+ ' . intval($customPro['log_validity']) . ' days', strtotime($currentTime))),
                                        'custommark' => 3,
                                    ));
                                }
                            }
                        }
                        # 添加门店收入记录
                        if ($payType != 3) {
                            if ($v['coupon_mark'] != 2) {
                                array_push($bizIncomeArr, array(
                                    'biz_id' => $orderInfo['biz_id'],
                                    'biz_income' => $v['pro_price'] - $v['coupon_price'],
                                    'pay_type' => $payType,
                                    'pay_create' => $currentTime,
                                    'member_id' => $memberId,
                                    'income_type' => 3,
                                    'pid' => $v['biz_pro_id'],
                                    'pay_year' => date('Y'),
                                    'pay_month' => date('m'),
                                    'pay_day' => date('d'),
                                    'custommark' => $v['custommark'],
                                    'order_number' => $orderNumber
                                ));
                            }
                        }


                    }
                }
                if ($demo) {
                    # 添加评论信息
                    Db::table('evaluation_score')->insertAll($evealuationArr);
                    # 添加门店收入
                    Db::table('biz_income')->insertAll($bizIncomeArr);
                    # 添加员工提成信息
                    if (!empty($deductArr)) {
                        Db::table("deduct")->insertAll($deductArr);
                    }
                    # 添加服务记录
                    if (!empty($logServiceArr)) {
                        Db::table('log_service')->insertAll($logServiceArr);
                    }
                    # 添加质保记录
                    if (!empty($warrantyArr)) {
                        Db::table('log_warranty')->insertAll($warrantyArr);
                    }
                    # 添加保养记录
                    if (!empty($maintainArr)) {
                        Db::table('log_maintain')->insertAll($maintainArr);
                    }
                    # 添加维修记录
                    if (!empty($repairArr)) {
                        Db::table('log_repair')->insertAll($repairArr);
                    }
                }
                if ($bizInfo['biz_type'] == 3 or $bizInfo['biz_type'] == 2) {
                    # 额外奖励
                    $settlement_gift = 0;
                    if ($bizInfo['recommend_status'] == 1 and $bizInfo['settlement_method'] == 3) {
                        # 门店推荐,
                        $settlement_gift = $bizInfo['settlement_gift'];
                    }
                    if ($settlementPrice > 0) {
                        # 添加结算
                        Db::table('biz_settlement')->insert(array(
                            'order_number' => $orderNumber,
                            'price' => getsPriceFormat($settlementPrice + $settlement_gift),
                            'tobe_settled' => getsPriceFormat($settlementPrice + $commissionPrice + $settlement_gift),
                            'type' => 1,
                            'method' => $payType,
                            'create_time' => $currentTime,
                            'order_price' => $setOrderCount,
                            'coupon_price' => $orderInfo['voucher_price'],
                            'commission_price' => $commissionPrice,
                            'biz_id' => $orderInfo['biz_id'],
                            'employee_sal' => $orderInfo['employee_sal']
                        ));
                    }
                    if (!$demo) {
                        Db::table('biz_income')->where(array('pid' => $orderNumber))->update(array('order_number' => $orderNumber, 'biz_income' => $commissionPrice));
                    } else {
                        # 合作店抽成(biz_income)
                        Db::table('biz_income')->insert(array(
                            'biz_id' => $orderInfo['biz_id'],
                            'biz_income' => $commissionPrice,
                            'pay_type' => $payType,
                            'pay_create' => $currentTime,
                            'member_id' => $memberId ?? 0,
                            'income_type' => 12,
                            'pid' => $orderNumber,
                            'pay_year' => date('Y', strtotime($currentTime)),
                            'pay_month' => date('m', strtotime($currentTime)),
                            'pay_day' => date('d', strtotime($currentTime)),
                            'pay_mode' => 1,
                            'order_number' => $orderNumber
                        ));
                    }
                }
                # 查最后一个推荐办理会员的人是不是合伙人
                $channel = Db::table('channel')->field('pid,channel,action_type')->where(array('member_id' => $memberId))->order('id desc')->find();
                if (!empty($channel) and $channel['action_type'] == 2 and ($channel['channel'] == 3 or $channel['channel'] == 5) and $channel['pid'] != 0 and $demo) {
                    $pInfo = DB::table('member_mapping')->field('member_type,member_level_id,member_expiration')->where("member_id = " . $channel['pid'])->find();
                    if (!empty($pInfo) and $pInfo['member_type'] == 2) {
                        if (($pInfo['member_level_id'] == 1) and $pInfo['member_expiration'] < date('Y-m-d')) {
                            # 过期,不是合伙人
                            Db::table('member_mapping')->where(array('member_id' => $channel['pid']))->update(array('member_type' => 1));
                        } else {
                            # 合伙人加收益,查询比例
                            $partnerSet = Db::table('sysset')->where(array('tagname' => 'partner_set'))->find();
                            if (!empty($partnerSet)) {
                                $info = json_decode($partnerSet['desc'], true);
                                if (!empty($info) and !empty($info['service_commission'])) {
                                    $partnerIncome = $payPrice * $info['service_commission'];
                                    if ($partnerIncome > 0) {
                                        Db::table('member_partner')->where(array('member_id' => $channel['pid']))->setInc('partner_balance', $partnerIncome);
                                        Db::table('member_partner')->where(array('member_id' => $channel['pid']))->setInc('partner_balance_total', $partnerIncome);
                                        Db::table('log_consump')->insert(array(
                                            'member_id' => $channel['pid'],
                                            'consump_price' => $partnerIncome,
                                            'consump_pay_type' => 1,
                                            'consump_time' => date('Y-m-d H:i:s'),
                                            'log_consump_type' => 2,
                                            'consump_type' => 1,
                                            'income_type' => 10,
                                            'biz_id' => $orderInfo['biz_id']
                                        ));
                                    }
                                }
                            }
                        }
                    }
                }
                # 是否为代理推荐？？
                if ($bizInfo['agent_id'] > 0 and $commissionPrice > 0) {
                    EalspellCommissionService::BizConsump($bizInfo['agent_id'], $commissionPrice, $orderInfo['biz_id'],$orderNumber);
                    EalspellCommissionService::BizSalesAchieved($bizInfo['agent_id'], $orderInfo['biz_id']);
                }
                $channel = Db::table("channel")->where(array("member_id"=>$memberId,"channel"=>10))->where("pid > 0")
                    ->order("id desc")->find();
                if(!empty($channel)){
                    EalspellCommissionService::memberConsumpNum($memberId,$channel['pid'],$orderNumber);
                    EalspellCommissionService::memberConsumpNumFinish($orderNumber,$memberId);
                }

                # 清除支付缓存状态查询
                $redis = new Redis();
                $redis->hDel('payRedis' . $orderInfo['biz_id'], $orderNumber);
                # 评论消息
                $this->template($orderNumber, $memberId, $orderInfo['biz_id']);
                # 完成服务任务
                TaskService::finishDayTask($orderInfo['biz_id'], 5);
                return array('status' => true, 'is_continue' => 2, 'msg' => '支付成功');
            } else {
                $redis = new Redis();
                $redis->hDel('payRedis' . $orderInfo['biz_id'], $orderNumber);
                return array('status' => false, 'msg' => '该订单已经处理过了,不可重复操作');
            }
        } else {
            return array('status' => false, 'msg' => '参数存在空值');
        }
    }

    function serviceInventDec($serviceId, $biz_id)
    {
        # 查询该服务是否有关联商品
        $relavice = Db::table("log_servicepro")->where(array("service_id" => $serviceId))->select();
        if (!empty($relavice)) {
            foreach ($relavice as $rk => $rv) {
                # 查询该商户库存是否足够
                $invent = Db::table("biz_invent")->where(array("biz_id" => $biz_id, "biz_pro_id" => $rv['pro_id']))->find();
                if (!empty($invent) and $invent['number'] > 0) {
                    # 判断剩余数量是否足够
                    if ($invent['number'] >= $rv['pro_num']) {
                        # 减去对应数量
                        Db::table("biz_invent")->where(array("biz_id" => $biz_id, "biz_pro_id" => $rv['pro_id']))->setDec("number", $rv['pro_num']);
                    } else {
                        # 直接为0
                        Db::table("biz_invent")->where(array("biz_id" => $biz_id, "biz_pro_id" => $rv['pro_id']))->update(array("number" => 0));
                    }
                }
            }

        }
        return true;
    }

    /**
     * @access public
     * @content 发送评论模板消息
     */
    function template($order_number, $memberId, $bizId)
    {
        # 接收订单编号
        if (!empty($order_number)) {
            # 查询订单对应的用户的openid
            $_openid = Db::table('member')
                ->field('member_openid')
                ->where(array('id' => $memberId))
                ->find();
            if (!empty($_openid)) {
                # 查询评论的站内消息模板
                $comment = Db::table('message')->where(array('message_type' => 1))->order(array('id' => 'desc'))->find();
                if (!empty($comment)) {
                    # 发送站内消息提醒  评论
                    $comments_res = Db::table('message_log')
                        ->insert(array('message_id' => $comment['id'], 'member_id' => $memberId,
                            'send_time' => date(("Y-m-d H:i:s"))));
                }
                if (!empty($_openid['member_openid']) and !is_null($_openid['member_openid'])) {
                    # 服务评价
                    $config = config('templateMsg.comment');
                    # 查询门店信息
                    $bizInfo = Db::table('biz')->field('biz_title')->where(array('id' => $bizId))->find();
                    $data = array(
                        'first' => array('value' => $config['first'], 'color' => '#000000'),
                        'keyword1' => array('value' => $bizInfo['biz_title'], 'color' => '#000000'),//门店名称
                        'keyword2' => array('value' => date('Y-m-d H:i:s'), 'color' => '#000000'), //消费时间
                        'remark' => array('value' => $config['remark'], 'color' => '#000000'),
                    );
                    $_res = ThirdParty::sendTemplate($_openid['member_openid'], '2FlURfQREBqmhE_K0CfhRUZXVyD-A-gtuNKD4QX1PTA', 'http://web.elianchefu.com/#/pages/mine/index', $data);
                    $getui = new IGeTuiService();
                    $getui->pushMessageToSingle($config['first'], $config['remark'], $memberId);
                }
            }
        }
    }

    /**
     * @param $mark
     * @param $order_number
     * @param $member_level_id
     * @param $member_expiration
     * @param $member_code
     * @param $car_level
     * @return bool
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     * @content 重新计算订单价格
     */
    function WriteOrderPrice($mark = false, $order_number, $member_level_id = 0, $member_expiration = '', $member_code = '', $car_level = '')
    {
        if ($mark) {
            # 查询所需参数信息
            $orderInfo = Db::table('orders')->field('car_level,member_id')->where(array('order_number' => $order_number))->find();
            $car_level = $orderInfo['car_level'];
            $memberInfo = Db::table('member_mapping')->field('member_level_id,member_expiration,member_code')->where(array('member_id' => $orderInfo['member_id']))->find();
            $member_level_id = $memberInfo['member_level_id'] ?? 0;
            $member_expiration = $memberInfo['member_expiration'];
            $member_code = $memberInfo['member_code'];

        }
        if ($member_level_id == 0) {
            $member_level_id_a = 1;
        } else {
            $member_level_id_a = $member_level_id;
        }
        # 判断会员状态
        if ($member_level_id > 0) {
            # 是会员,
            if (($member_level_id == 1) and $member_expiration < date('Y-m-d')) {
                if (!empty($member_code)) {
                    $level = 'code';
                } else {
                    $level = 'noCode';
                }
            } else {
                $level = 'member';
            }
        } else {
            if (!empty($member_code)) {
                $level = 'code';
            } else {
                $level = 'noCode';
            }
        }
        # 查询订单车牌号、用户id
        $orderinfo = Db::table("orders")->field("car_liences, member_id,biz_id")
            ->where(array("order_number" => $order_number))->find();
        $this->bizId = $orderinfo['biz_id'];
        if ($this->bizId == 1) {
            $this->bizId = 0;
        }
        # 查询服务工单,商品工单
        # 服务工单
        $orderServer = Db::table('order_server')
            ->field("id,server_id,price,custommark,price_lock,
            if(custommark=1,(select biz_pid from service where id = server_id),1) biz_pid")
            ->where(array('order_number' => $order_number))->select();
        $orderBiz = Db::table('order_biz')
            ->field("id,biz_pro_id,pro_price,custommark,price_lock,bizpro_number")
            ->where(array('order_number' => $order_number))->select();
        # 订单差价
        $diffPrice = 0;
        if (!empty($orderServer)) {
            foreach ($orderServer as $k => $v) {
                if ($v['custommark'] == 1) {
                    # 系统服务
                    # 查询对应车辆等级对应的服务价格
                    if ($level != 'noCode') {
                        # 注册/会员
                        $_discount = Db::table("service_car_mediscount")->field(array("discount"))
                            ->where(array("service_id" => $v['server_id'], 'car_level_id' => $car_level, 'service_type' => 1, 'biz_id' => $this->bizId))
                            ->value('discount');
                    } else {
                        # 未注册不是会员
                        $_discount = Db::table("service_car_mediscount")->field(array("discount"))
                            ->where(array("service_id" => $v['server_id'], 'car_level_id' => $car_level, 'service_type' => 2, 'biz_id' => $this->bizId))
                            ->value('discount');
                    }
                    if (empty($_discount)) {
                        if ($level != 'noCode') {
                            # 注册/会员
                            $_discount = Db::table("service_car_mediscount")
                                ->where(array("service_id" => $v['server_id'], 'service_type' => 1, 'biz_id' => $this->bizId))
                                ->max('discount');
                        } else {
                            # 未注册不是会员
                            $_discount = Db::table("service_car_mediscount")
                                ->where(array("service_id" => $v['server_id'], 'service_type' => 2, 'biz_id' => $this->bizId))
                                ->max('discount');
                        }
                    }
                    $_res_discount = sprintf("%.2f", $_discount);
                    Db::table("order_server")->where(array('id' => $v['id']))->update(array("original_price" => $_res_discount));
                    /*if ($level != 'member') {
                        if (!empty($_res_discount) and !is_null($_res_discount)) {
                            if ($_res_discount != $v['price'] and $v['price_lock'] == 1) {
                                # 计算差价
//                                $diffPrice = $diffPrice + ($v['price'] - $_res_discount);
                                $diffPrice = $diffPrice + $_res_discount;
                                #修改工单价格
                                Db::table("order_server")->where(array('id' => $v['id']))->update(array("price" => $_res_discount));
                            } else {
                                $diffPrice = $diffPrice + $v['price'];
                            }
                        } else {
                            $diffPrice = $diffPrice + $v['price'];
                        }
                    } else {*/
                    # 查询当前服务是否与当前会员绑定
                    $relevance_service = Db::table('relevance_service rs')
                        ->field('discount,car_impose')
                        ->where(array('rs.service_id' => $v['server_id']))
                        ->where("rs.privilege_id in 
                            (select p.id from privilege p where p.privilege_relevance=1 and find_in_set(p.id,(select level_privilege from level_content lc 
                            where lc.level_id = " . $member_level_id . ")))")
                        ->find();
                    if (!empty($relevance_service)) {
                        if (!empty($orderinfo['member_id'])) {
                            # 查询当前车辆是否在限制内
                            if ($relevance_service['car_impose'] > 0) {
                                $car_in_impose = Db::query("select id from member_car where member_id = {$orderinfo['member_id']} and  '{$orderinfo['car_liences']}' in 
                                          (select t.car_licens from (select car_licens from member_car 
                                          where member_id = {$orderinfo['member_id']} order by id asc limit {$relevance_service['car_impose']} ) as t )");
                                if (!empty($car_in_impose)) {
                                    $member_level_discount = $relevance_service;
                                } else {
                                    goto sysdiscount;
                                }
                            } else {
                                $member_level_discount = $relevance_service;
                            }
                        } else {
                            goto sysdiscount;
                        }
                    } else {
                        # 查询会员折扣
                        # 查询当前服务下会员折扣
                        sysdiscount:
                        $member_level_discount = Db::table("service_mediscount")
                            ->field(array("discount"))->where(array("service_id" => $v['server_id'], 'member_level' => $member_level_id_a))->find();
                    }
                    if (empty($member_level_discount['discount']) or is_null($member_level_discount['discount']) or $member_level_discount['discount'] == 1) {
                        $_res_memberdiscount = 1;
                    } else {
                        # 门店下单(合作端上架的服务)不打折
                        if ($v['biz_pid'] == 0) {
                            # 平台服务 不是余额支付 不打折
//                            $_res_memberdiscount = floatval($member_level_discount['discount']);
                            $_res_memberdiscount = 1;
                        } else {
                            # 合作端上架的服务 不打折
                            $_res_memberdiscount = 1;
                        }
                    }
                    if (!empty($_res_discount) and !is_null($_res_memberdiscount)) {
                        $_res_price = sprintf("%.2f", $_res_discount) * $_res_memberdiscount;
                    }
                    if (!is_null($_res_price) and floatval($_res_price) >= 0) {
                        if ($_res_price != $v['price'] and $v['price_lock'] == 1) {
                            # 计算差价
//                                $diffPrice = $diffPrice + ($v['price'] - $_res_discount);
                            $diffPrice = $diffPrice + $_res_price;
                            #修改工单价格
                            Db::table("order_server")->where(array('id' => $v['id']))->update(array("price" => $_res_price));
                        } else {
                            $diffPrice = $diffPrice + $v['price'];
                        }
                    } else {
                        $diffPrice = $diffPrice + $v['price'];
                    }
//                    }
                } else {
                    # 查询服务原价
                    $custom_price = Db::table("customserver")->field(array("custom_server_price"))
                        ->where(array("id" => $v['server_id']))->find();
                    # 自定义服务
                    if ($level == 'member') {
                        $price = floatval($v['price']);
//                        $discount = getsCustomServerDescount($member_level_id, 2);
                        # 门店下单不打折
                        $discount = 1;
                        if (floatval($custom_price['custom_server_price']) * $discount != $price and $v['price_lock'] == 1) {
                            # 计算差价
//                            $diffPrice = $diffPrice + ($price - ($custom_price['custom_server_price'] * $discount));
                            $diffPrice = $diffPrice + floatval($custom_price['custom_server_price']) * $discount;
                            Db::table("order_server")->where(array('id' => $v['id']))
                                ->update(array("price" => floatval($custom_price['custom_server_price']) * $discount));
                        } else {
                            $diffPrice = $diffPrice + $v['price'];
                        }
                    } else {
                        Db::table("order_server")->where(array('id' => $v['id']))->update(array("price" => $custom_price['custom_server_price']));
                        $diffPrice = $diffPrice + $custom_price['custom_server_price'];
                    }
                }
            }
        }
        # 商品工单
        if (!empty($orderBiz)) {
            foreach ($orderBiz as $k => $v) {
                if ($v['custommark'] == 2) {
                    # 自定义商品查询原价
                    $price = Db::table("custom_biz")->field("custom_biz_price")->where(array('id' => $v['biz_pro_id']))->find();
                    if ($level == 'member') {
                        if ($v['custommark'] == 2) {
                            # 自定义商品
                            $order_price = floatval($v['pro_price']);
                            # 引入折扣
//                            $discount = getsCustomServerDescount($member_level_id, 1);
                            # 门店下单不打折
                            $discount = 1;
                            if (floatval(($price['custom_biz_price'] * $discount * $v['bizpro_number'])) != $order_price and $v['price_lock'] == 1) {
                                # 计算差价
//                            $diffPrice = $diffPrice + ($order_price - ($price['custom_biz_price'] * $discount * $v['bizpro_number']));
                                $diffPrice = $diffPrice + floatval($price['custom_biz_price'] * $discount * $v['bizpro_number']);
                                Db::table("order_biz")
                                    ->where(array("id" => $v['id']))
                                    ->update(array("pro_price" => floatval($price['custom_biz_price'] * $discount * $v['bizpro_number'])));
                            } else {
                                $diffPrice = $diffPrice + $v['pro_price'];
                            }
                        }
                    } else {
                        $diffPrice = $diffPrice + $price['custom_biz_price'] * $v['bizpro_number'];
                        Db::table("order_biz")
                            ->where(array("id" => $v['id']))
                            ->update(array("pro_price" => floatval($price['custom_biz_price'] * $v['bizpro_number'])));
                    }
                } else {
                    # 系统商品
//                    if ($level == 'member') {
                    # 会员
                    $_shop_discount = Db::table("biz_pro_mediscount")->field("discount")
                        ->where(array("biz_pro_id" => $v['biz_pro_id'], "member_level" => $member_level_id_a))->find();
                    if (!is_null($_shop_discount['discount']) and $_shop_discount['discount'] != 1) {
                        $_shop_price = Db::table("biz_pro")->field("biz_pro_online")->where(array("id" => $v['biz_pro_id']))->find();
                        if (!is_null($_shop_price['biz_pro_online'])) {
                            $_res_shopdiscount = floatval($_shop_price['biz_pro_online']) * floatval($_shop_discount['discount']) * $v['bizpro_number'];
                            $_res_shopdiscount = sprintf('%.2f', $_res_shopdiscount);
                            if ($_res_shopdiscount != floatval($v['pro_price']) and $v['price_lock'] == 1) {
                                Db::table("order_biz")->where(array('id' => $v['id']))->update(array("pro_price" => $_res_shopdiscount));
                            }
                        }
                    }
//                    }
                    /* else {
                         # 不是会员,判断注册没注册
                         if ($level == 'code') {
                             $_shop_price = Db::table("biz_pro")->field("biz_pro_online")->where(array("id" => $v['biz_pro_id']))->find();
                             if (!is_null($_shop_price['biz_pro_online'])) {
                                 if (floatval($_shop_price['biz_pro_online'] * $v['bizpro_number']) != floatval($v['pro_price']) and $v['price_lock'] == 1) {
                                     Db::table("order_biz")->where(array('id' => $v['id'])
                                     )->update(array("pro_price" => floatval($_shop_price['biz_pro_online'] * $v['bizpro_number'])));
                                 }
                             }
                         }
                     }*/
                }
            }
        }
        # 修改订单总价
        Db::table('orders')->where(array('order_number' => $order_number))->update(array('order_price' => $diffPrice));
//        # 完成任务
//        BizTask::FinishTask(3, $orderinfo['biz_id'], 1);

        return true;
    }


    /**
     * @param $biz_id
     * @param $order_number
     * @param $memberId
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @content 查询订单支付价格
     */
    function countPay($biz_id, $order_number, $memberId, $mark = false, $payType = 0)
    {
        if ($biz_id == 1) {
            $biz_id = 0;
        }
        # 根据订单编号查询车辆等级
        $orderCarInfo = Db::table('orders')->field('car_level')->where(array('order_number' => $order_number))->find();
        $carLevel = $orderCarInfo['car_level'];
        if (!empty($order_number)) {
            $ordercount = Db::table('orders o')
                ->field("o.id,
                (select sum(os.price) from order_server os where os.order_number=o.order_number and os.status = 4 and os.coupon_mark = 1) servercount,
                (select sum(ob.pro_price) from order_biz ob where ob.order_number = o.order_number and ob.status = 2 and ob.coupon_mark = 1) bizcount,
                (select sum(ob.coupon_price) from order_biz ob where ob.order_number = o.order_number and ob.status = 2 and ob.coupon_mark = 1) bizcouponcount
                ")
                ->where(array('o.order_number' => $order_number))
                ->find();
            if ($mark) {
                dump($ordercount);
            }
            if (!empty($ordercount)) {
                #用户会员等级初始化
                $memberLevelId = 0;
                $memberBalance = 0;
                # 判断用户的会员等级
                if (!empty($memberId) and !is_null($memberId)) {
                    # 查询用户的会员等级.过期时间,服务吗
                    $memberInfo = Db::table('member_mapping')->field('member_level_id,member_expiration,member_code,member_balance')
                        ->where(array('member_id' => $memberId))->find();
                    if (!empty($memberInfo)) {
                        $memberBalance = $memberInfo['member_balance'];
                        if (!empty($memberInfo['member_level_id']) and !is_null($memberInfo['member_level_id'])) {
                            if ($memberInfo['member_level_id'] == 1) {
                                if (date('Y-m-d') > $memberInfo['member_expiration']) {
                                    if (!empty($memberInfo['member_code']) and !is_null($memberInfo['member_code'])) {
                                        $memberLevelMark = 'online';# 体验卡会员已过期,已经注册--------------------->线上价格无折扣
                                    } else {
                                        $memberLevelMark = 'biz';# 体验卡会员已过期,没有注册-------------------------门店价格无折扣
                                    }
                                } else {
                                    $memberLevelMark = 'onlineLevel';# 体验卡会员,已经注册----------------------线上价格有折扣
                                    $memberLevelId = $memberInfo['member_level_id'];
                                }
                            } else {
                                $memberLevelMark = 'onlineLevel';# 其他等级会员,已经注册------------------------线上价格有折扣
                                $memberLevelId = $memberInfo['member_level_id'];
                            }
                        } else {
                            if (!empty($memberInfo['member_code']) and !is_null($memberInfo['member_code'])) {
                                $memberLevelMark = 'online';# 不是会员,但是已经注册---------------------------------线上价格无折扣
                            } else {
                                $memberLevelMark = 'biz';# 不是会员,没有注册----------------------------------------门店价格无折扣
                            }
                        }
                    } else {
                        $memberLevelMark = 'biz';# 未查到用户信息---------------------------------------------------门店价格无折扣
                    }
                } else {
                    $memberLevelMark = 'biz';# 没有用户信息---------------------------------------------------------门店价格无折扣
                }
                if ($memberLevelId == 0) {
                    $member_level_id_a = 1;
                } else {
                    $member_level_id_a = $memberLevelId;
                }
                # 查询该订单下的服务(查询每个服务是否支持微信支付)
                $orderServer = Db::table('order_server')
                    ->field('id,server_id,custommark,price,price_lock,original_price,coupon_price,
                    if(custommark=1,(select biz_pid from service where id = server_id),1) biz_pid')
                    ->where(array('order_number' => $order_number, 'status' => 4))
                    ->select();
                # 服务工单微信支付总价
                $orderServerPriceWx = 0;
                # 服务工单其他支付方式总价
                $orderServerPriceOther = 0;
                # 服务工单余额支付总价
                $orderServerPriceB = 0;
                $orderServerPriceC = 0;
                # 服务原价
                $originalPrice = 0;
                if (!empty($orderServer)) {
                    foreach ($orderServer as $k => $v) {
                        $originalPrice += $v['original_price'];
                        if ($v['price_lock'] == 0) {
                            $orderServerPriceWx = $orderServerPriceWx + $v['price'];
                            $orderServerPriceOther = $orderServerPriceOther + $v['price'];
                            $orderServerPriceB = $orderServerPriceB + $v['price'];
                            $orderServerPriceC = $orderServerPriceC + $v['price'];
                        } else {
                            # 查询当前服务是否与当前会员绑定
                            $relevance_service = Db::table('relevance_service rs')
                                ->field('discount,car_impose')
                                ->where(array('rs.service_id' => $v['server_id']))
                                ->where("rs.privilege_id in 
                            (select p.id from privilege p where p.privilege_relevance=1 and find_in_set(p.id,(select level_privilege from level_content lc 
                            where lc.level_id = " . $memberLevelId . ")))")
                                ->find();
                            if (!empty($relevance_service)) {
                                if (!empty($orderinfo['member_id'])) {
                                    # 查询当前车辆是否在限制内
                                    if ($relevance_service['car_impose'] > 0) {
                                        $car_in_impose = Db::query("select id from member_car where member_id = {$orderinfo['member_id']} and  '{$orderinfo['car_liences']}' in 
                                          (select t.car_licens from (select car_licens from member_car 
                                          where member_id = {$orderinfo['member_id']} order by id asc limit {$relevance_service['car_impose']} ) as t )");
                                        if (!empty($car_in_impose)) {
                                            $member_level_discount = $relevance_service;
                                        } else {
                                            goto sysdiscount;
                                        }
                                    } else {
                                        $member_level_discount = $relevance_service;
                                    }
                                } else {
                                    goto sysdiscount;
                                }
                            } else {
                                # 查询会员折扣
                                # 查询当前服务下会员折扣
                                sysdiscount:
                                $member_level_discount = Db::table("service_mediscount")
                                    ->field(array("discount"))->where(array("service_id" => $v['server_id'], 'member_level' => $member_level_id_a))->find();
                                if ($mark) {
                                    dump($v['server_id']);
                                    dump($member_level_id_a);
                                    dump($member_level_discount);
                                }
                            }
                            if (empty($member_level_discount) or is_null($member_level_discount['discount']) or $member_level_discount['discount'] == 1) {
                                $_res_memberdiscount = 1;
                            } else {
                                # 门店下单(合作端上架的服务)不打折
                                if ($v['biz_pid'] == 0) {
                                    # 平台服务 不是余额支付 不打折
                                    $_res_memberdiscount = floatval($member_level_discount['discount']);
                                } else {
                                    # 合作端上架的服务 不打折
                                    $_res_memberdiscount = 1;
                                }
                            }
                            if ($v['custommark'] == 1) {
                                if ($carLevel == 0) {
                                    $carLevel = 1;
                                }
                                $serverInfoOnline = Db::table('service s')
                                    ->field('service_wxpay,discount')
                                    ->join('service_car_mediscount sc', 'sc.service_id=s.id', 'left')
                                    ->where(array('sc.car_level_id' => $carLevel, 'sc.service_type' => 1, 'sc.biz_id' => $biz_id, 's.id' => $v['server_id']))
                                    ->find();
                                $serverInfoBiz = Db::table('service s')
                                    ->field('service_wxpay,discount')
                                    ->join('service_car_mediscount sc', 'sc.service_id=s.id', 'left')
                                    ->where(array('sc.car_level_id' => $carLevel, 'sc.service_type' => 2, 'sc.biz_id' => $biz_id, 's.id' => $v['server_id']))
                                    ->find();
                                # 判断用户会员等级
                                if ($memberLevelMark == 'biz') {
                                    #门店价格无折扣
                                    # 服务工单其他支付方式总价
                                    $orderServerPriceOther = getsPriceFormat($orderServerPriceOther + $serverInfoBiz['discount']);
                                    # 服务工单微信支付总价
                                    $orderServerPriceWx = getsPriceFormat($orderServerPriceWx + floatval($serverInfoBiz['discount']));
                                    # 余额
                                    $orderServerPriceB = getsPriceFormat($orderServerPriceB + floatval($serverInfoBiz['discount']) * $_res_memberdiscount);
                                    $orderServerPriceC = getsPriceFormat($orderServerPriceC + floatval($serverInfoBiz['discount']) * $_res_memberdiscount);
                                    $sp = $serverInfoBiz['discount'];
                                } elseif ($memberLevelMark == 'online') {
                                    #线上价格无折扣
                                    # 服务工单其他支付方式总价
                                    $orderServerPriceOther = getsPriceFormat($orderServerPriceOther + $serverInfoOnline['discount']);
                                    # 服务工单微信支付总价
                                    $orderServerPriceWx = getsPriceFormat($orderServerPriceWx + floatval($serverInfoOnline['discount']));
                                    # 余额
                                    $orderServerPriceB = getsPriceFormat($orderServerPriceB + floatval($serverInfoOnline['discount']) * $_res_memberdiscount);
                                    $orderServerPriceC = getsPriceFormat($orderServerPriceC + floatval($serverInfoOnline['discount']) * $_res_memberdiscount);
                                    $sp = $serverInfoOnline['discount'];
                                } elseif ($memberLevelMark == 'bizLevel') {
                                    # 门店价格有折扣
                                    # 查询对应的会员等级折扣
                                    $service_discount = Db::table('service_mediscount')->field('discount')
                                        ->where(array('service_id' => $v['server_id'], 'member_level' => $memberLevelId))
                                        ->find();
                                    # 服务工单其他支付方式总价
                                    $orderServerPriceOther = getsPriceFormat($orderServerPriceOther + $serverInfoBiz['discount']);
                                    # 余额
                                    $orderServerPriceB = getsPriceFormat($orderServerPriceB + floatval($serverInfoBiz['discount']) * $_res_memberdiscount);
                                    $orderServerPriceC = getsPriceFormat($orderServerPriceC + floatval($serverInfoBiz['discount']) * $_res_memberdiscount);
                                    $sp = $serverInfoBiz['discount'];
                                    if (!empty($service_discount)) {
                                        # 是否推荐微信支付
                                        if ($serverInfoOnline['service_wxpay'] == 2) {
                                            // * $service_discount['discount']
                                            $orderServerPriceWx = getsPriceFormat($orderServerPriceWx + $serverInfoBiz['discount']);
                                        } else {
                                            $orderServerPriceWx = getsPriceFormat($orderServerPriceWx + floatval($serverInfoBiz['discount']));
                                        }
                                    } else {
                                        # 未查询到折扣
                                        # 服务工单微信支付总价
                                        $orderServerPriceWx = getsPriceFormat($orderServerPriceWx + floatval($serverInfoBiz['discount']));
                                    }
                                } else {
                                    # 线上价格有折扣
                                    # 查询对应的会员等级折扣
                                    $service_discount = Db::table('service_mediscount')->field('discount')
                                        ->where(array('service_id' => $v['server_id'], 'member_level' => $memberLevelId))
                                        ->find();
                                    # 服务工单其他支付方式总价
                                    $orderServerPriceOther = getsPriceFormat($orderServerPriceOther + $serverInfoOnline['discount']);
                                    # 余额
                                    $orderServerPriceB = getsPriceFormat($orderServerPriceB + floatval($serverInfoOnline['discount']) * $_res_memberdiscount);
                                    $orderServerPriceC = getsPriceFormat($orderServerPriceC + floatval($serverInfoOnline['discount']) * $_res_memberdiscount);
                                    $sp = $serverInfoOnline['discount'];
                                    if (!empty($service_discount)) {
                                        # 是否推荐微信支付
                                        if ($serverInfoOnline['service_wxpay'] == 2) {
                                            //* $service_discount['discount']
                                            $orderServerPriceWx = getsPriceFormat($orderServerPriceWx + $serverInfoOnline['discount']);
                                        } else {
                                            $orderServerPriceWx = getsPriceFormat($orderServerPriceWx + floatval($serverInfoOnline['discount']));
                                        }
                                    } else {
                                        # 未查询到折扣
                                        # 服务工单微信支付总价
                                        $orderServerPriceWx = getsPriceFormat($orderServerPriceWx + floatval($serverInfoOnline['discount']));
                                    }
                                }
                                if ($payType == 5) {
                                    $oprice = floatval($sp) * $_res_memberdiscount;
                                    $p = $oprice - $v['coupon_price'];
                                    if ($p < 0) {
                                        $p = 0;
                                    }
                                    Db::table('order_server')->where(array('id' => $v['id']))->update(array('original_price' => $oprice, 'price' => $p));
                                }
                            } else {
                                # 自定义服务
                                $orderServerPriceWx = getsPriceFormat($orderServerPriceWx + $v['original_price']);# 服务工单微信支付总价
                                $orderServerPriceOther = getsPriceFormat($orderServerPriceOther + $v['original_price']);# 服务工单其他支付方式总价
                                # 余额
                                $orderServerPriceB = getsPriceFormat($orderServerPriceB + floatval($v['original_price']));
                                $orderServerPriceC = getsPriceFormat($orderServerPriceC + floatval($v['original_price']));
                            }
                        }
                        $a = $orderServerPriceB - floatval($v['coupon_price']);
                        if ($a < 0) {
                            $a = 0;
                        }
                        $orderServerPriceB = getsPriceFormat($a);
                    }
                }
                # 查询该订单下的商品(查询每个商品是否支持微信支付)
                $orderPro = Db::table('order_biz')
                    ->field("biz_pro_id,custommark,pro_price,price_lock,bizpro_number,original_pro_price")
                    ->where(array('order_number' => $order_number, 'status' => 2))
                    ->select();
                # 商品工单微信支付总价
                $orderProPriceWx = 0;
                # 商品工单其他支付方式总价
                $orderProPriceOther = 0;
                if (!empty($orderPro)) {
                    foreach ($orderPro as $k => $v) {
                        $originalPrice += $v['original_pro_price'];
                        if ($v['price_lock'] == 0) {
                            $orderServerPriceWx = $orderServerPriceWx + $v['pro_price'];
                            $orderServerPriceOther = $orderServerPriceOther + $v['pro_price'];
                        } else {
                            if ($v['custommark'] == 1) {
                                # 查询商品门店价格和线上价格以及是否推荐微信支付
                                $proInfo = Db::table('biz_pro')->field('biz_pro_price,biz_pro_online,biz_pro_wxpay')->where(array('id' => $v['biz_pro_id']))->find();
                                if ($memberLevelMark == 'biz') {
                                    #门店价格无折扣
                                    # 商品工单其他支付方式总价
                                    $orderProPriceOther = getsPriceFormat($orderProPriceOther + $proInfo['biz_pro_price'] * intval($v['bizpro_number']));
                                    # 商品工单微信支付总价
                                    $orderProPriceWx = getsPriceFormat($orderProPriceWx + $proInfo['biz_pro_price'] * intval($v['bizpro_number']));
                                } elseif ($memberLevelMark == 'online') {
                                    #线上价格无折扣
                                    # 商品工单其他支付方式总价
                                    $orderProPriceOther = getsPriceFormat($orderProPriceOther + $proInfo['biz_pro_online'] * intval($v['bizpro_number']));
                                    # 商品工单微信支付总价
                                    $orderProPriceWx = getsPriceFormat($orderProPriceWx + $proInfo['biz_pro_online'] * intval($v['bizpro_number']));
                                } elseif ($memberLevelMark == 'bizLevel') {
                                    # 门店价格有折扣
                                    #查询该商品对应的会员等级折扣
                                    $proDiscount = Db::table('biz_pro_mediscount')
                                        ->field('discount')
                                        ->where(array('biz_pro_id' => $v['biz_pro_id'], 'member_level' => $memberLevelId))
                                        ->find();
                                    # 商品工单其他支付方式总价
                                    $orderProPriceOther = getsPriceFormat($orderProPriceOther + $proInfo['biz_pro_price'] * intval($v['bizpro_number']));
                                    if (!empty($proDiscount)) {
                                        # 商品工单微信支付总价 * $proDiscount['discount']
                                        $orderProPriceWx = getsPriceFormat($orderProPriceWx + $proInfo['biz_pro_price'] * intval($v['bizpro_number']));
                                    } else {
                                        # 未查询到折扣信息
                                        # 商品工单微信支付总价
                                        $orderProPriceWx = getsPriceFormat($orderProPriceWx + $proInfo['biz_pro_price'] * intval($v['bizpro_number']));
                                    }
                                } else {
                                    # 线上价格有折扣
                                    #查询该商品对应的会员等级折扣
                                    $proDiscount = Db::table('biz_pro_mediscount')->field('discount')
                                        ->where(array('biz_pro_id' => $v['biz_pro_id'], 'member_level' => $memberLevelId))->find();
                                    # 商品工单其他支付方式总价
                                    $orderProPriceOther = getsPriceFormat($orderProPriceOther + $proInfo['biz_pro_online'] * intval($v['bizpro_number']));
                                    if (!empty($proDiscount)) {
                                        # 商品工单微信支付总价 * $proDiscount['discount']
                                        $orderProPriceWx = getsPriceFormat($orderProPriceWx + $proInfo['biz_pro_online'] * intval($v['bizpro_number']));
                                    } else {
                                        # 未查询到折扣信息
                                        # 商品工单微信支付总价
                                        $orderProPriceWx = getsPriceFormat($orderProPriceWx + $proInfo['biz_pro_online'] * intval($v['bizpro_number']));
                                    }
                                }
                            } else {
                                # 自定义服务
                                $orderProPriceWx = getsPriceFormat((floatval($orderProPriceWx) + floatval($v['original_pro_price'])));# 商品工单微信支付总价
                                $orderProPriceOther = getsPriceFormat((floatval($orderProPriceOther) + (floatval($v['original_pro_price']))));# 商品工单其他支付方式总价
                            }
                        }
                    }
                }
                # 余额支付总金额
//                $price = getsPriceFormat((floatval($ordercount['servercount'])) + floatval($ordercount['bizcount']) - floatval($ordercount['bizcouponcount']));
                $price = getsPriceFormat($orderServerPriceB + floatval($ordercount['bizcount']) - floatval($ordercount['bizcouponcount']));
                # 微信支付总金额
                $wxPrice = getsPriceFormat((floatval($orderProPriceWx) + floatval($orderServerPriceWx) - floatval($ordercount['bizcouponcount'])));
                # 其他方式支付总金额
                $otherPrice = getsPriceFormat((floatval($orderProPriceOther) + floatval($orderServerPriceOther) - floatval($ordercount['bizcouponcount'])));
                # 判断该订单是否使用了现金抵值券
                /*  $cashCoupon = Mysql('mysql')->table('log_cashcoupon')->where(array('order_number' => $order_number, 'create_time' => date("Y-m-d")))->fetchType(2)->select();*/
                /*voucher_type neq 3 and voucher_type neq 4 and voucher_type neq 7 and voucher_type neq 8 and*/
                $cashCoupon = Db::table('log_cashcoupon')
                    ->field('voucher_price,voucher_type')
                    ->where(array('order_number' => $order_number))//, 'create_time' => date('Y-m-d')
                    ->find();
                if (!empty($cashCoupon)) {
                    $redPacketVoucherPriceCount = getsPriceFormat($cashCoupon['voucher_price']);
                    if ($redPacketVoucherPriceCount > 0) {
                        if ($cashCoupon['voucher_type'] != 3 and $cashCoupon['voucher_type'] != 4 and $cashCoupon['voucher_type'] != 7 and $cashCoupon['voucher_type'] != 8) {
                            # 余额支付总金额
                            $price = getsPriceFormat(($price - $redPacketVoucherPriceCount));
                        }
                        if ($cashCoupon['voucher_type'] != 7 and $cashCoupon['voucher_type'] != 8) {
                            # 微信支付总金额
                            $wxPrice = getsPriceFormat(($wxPrice - $redPacketVoucherPriceCount));
                            # 其他方式支付总金额
                            $otherPrice = getsPriceFormat(($otherPrice - $redPacketVoucherPriceCount));

                        }
                    }
                }
                $priceC = getsPriceFormat($orderServerPriceC + floatval($ordercount['bizcount']) - floatval($ordercount['bizcouponcount']));
                if ($payType == 5) {
                    Db::table('orders')->where(array('order_number' => $order_number))->update(array('order_price' => $priceC));
                }
                # 判断当前用户余额 大于 余额支付的价格 正常打折  不大于 不打折
                if ($priceC > $memberBalance) {
                    $price = $wxPrice;
                }
                # 判断余额是否足够
                if ($price > $memberBalance) {
                    # 不能使用余额支付
                    $payB = 2;
                } else {
                    $payB = 1;
                }
                return array('status' => true, 'price' => $price, 'priceC' => $priceC, 'payB' => $payB, 'payB_text' => '余额不足,请使用其他支付方式', 'wxPrice' => $wxPrice, 'otherPrice' => $otherPrice, 'originalPrice' => $originalPrice);
            } else {
                return array('status' => false, 'msg' => '订单详情为空');
            }
        } else {
            return array('status' => false, 'msg' => '订单编号为空');
        }
    }
}
